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.
On the server side, we have a tiny file called random_number.php which simply outputs a random number between 0 and 9999.
This example is extremely simple, but it doesn’t get a whole lot more complicated as jQuery also makes it very easy to handle:
- Different datatypes – XML, Json, script and HTML.
- 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!).