Thanks to the jQuery library, Ajax transactions are a breeze. All you have to do is send an Ajax request off to the server and display the results. The example below sends a request to random_number.php on the server when the user clicks on a button. When a result is successfully returned, it is displayed in a div and the style of the div is updated.
In your view file, create your button and result div. Then add a JavaScript listener to your button which will send the Ajax request when the button is clicked.
[snippet id=”133″]
On the server side, we have a tiny file called random_number.php which simply outputs a random number between 0 and 9999.
[snippet id=”134″]
This example is extremely simple, but it doesn’t get a whole lot more complicated as jQuery also makes it very easy to handle:
- Errors.
- Different datatypes – XML, Json, script and HTML.
- Caching
- Handle specific HTTP responses (i.e. 404)
- and perform a variety of other functions;
See the jQuery docs for more information about jQuery.ajax().
You can run this script here. Just click the button on the right hand side to generate a new random number (over and over again if you wish!).