The built-in JavaScript framework provides simple but powerful AJAX capabilities. In most cases, you don't need to write JavaScript code to post data to the server and update elements of your page. The data-
attributes can solve a lot of typical tasks. For more complex cases you can employ the full power of JavaScript. You can find more information in the documentation. Check out the calculator example below!
The markup defines a form with the inputs for numbers, operation and buttons. Note the data-request
and data-request-update
attributes on the FORM tag. Those two attributes tell the AJAX framework which PHP function must handle the request and what page element must be updated when the result comes back from the server.
<form role="form" data-request="onTest" data-request-update="calcresult: '#result'"> <input type="text" value="15" name="value1"> <label><input type="radio" name="operation" value="+"> +</label> <label><input type="radio" name="operation" value="-"> -</label> <label><input type="radio" name="operation" value="*" checked> *</label> <label><input type="radio" name="operation" value="/"> /</label> <input type="text" value="5" name="value2"> <button type="submit">=</button> </form> <!-- The result --> <div id="result">{% partial "calcresult" %}"</div>
The partial is referred in the form's data-request-update
attribute together with the ID of the element that must be updated with the AJAX request. The partial is also rendered when the page first loads to display the default value.
{{ result|default(75) }}
That PHP function is referred in the form's data-request
attribute and acts as the AJAX handler. It loads the submitted values, performs the requested operation, and assigns the calculated value to the result page variable, which is then used in the calcresult partial. The function is defined right in the page file, in the PHP section.
function onTest() { $value1 = input('value1'); $value2 = input('value2'); $operation = input('operation'); switch ($operation) { case '+' : $this['result'] = $value1 + $value2; break; case '-' : $this['result'] = $value1 - $value2; break; case '*' : $this['result'] = $value1 * $value2; break; default : $this['result'] = $value2 != 0 ? round($value1 / $value2, 2) : 'NaN'; break; } }
Segera hubungi Account Manager kami di nomor WA berikut : 0812-7355-7000