Simple Ajax request with jQuery

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.

    <!--This is the button -->
    <button type="button" class="btn btn-lg btn-primary" id="generateButton">Generate Number</button>
    
    <!-- This is the div that contains the result -->
    <div class="panel-default" id="result_div">
    	The result will appear here.
    </div>
    
    <!-- This is the JavaScript that listens for a click and then sends the request -->
    <script>
    	$("#generateButton").click(function(){ //when "generateButton" is clicked
			$.ajax({ //create an ajax request
				url:"http://showcase.denishogan.ie/ajax/random_number.php", // this is the url to send the request to
				success:function(result){ // on success
					$("#result_div").html(result); // display the resulting html (or in our case, simple old text) in the div with an id of "result_div"
					$("#target-panel").removeClass("panel-default"); //as we are at it, remove the old style of the result container
					$("#target-panel").addClass("panel-success"); //add a new style so it turns green
				}
			});
		}); 
	</script>
    
    

On the server side, we have a tiny file called random_number.php which simply outputs a random number between 0 and 9999.

<?php
    //output a random number between 0 & 9999
    echo "<b>Random Number:</b> ".rand(0, 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:

  • 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!).

Leave a Comment

Your email address will not be published. Required fields are marked *