If you are building some web-app that needs to execute AJAX requests, you must use jQuery to perform these AJAX requests. jQuery has great AJAX support and it is very easy to perform AJAX requests using jQuery. It is less code to write too.

How to Load AJAX Content with jQuery

The Basic Usage

  url: "http://www.thedeveloper24.com",
    alert(data); /* alert AJAX response */

This basic code will send an AJAX (GET) request to http://www.thedeveloper24.com and will show the received response.

The Complete Code

  url: "http://www.thedeveloper24.com/",
  type: "GET",
  data: { postVar1: 'theValue1', postVar2: 'theValue2' }, /* the get parameters to pass */
    //show loading spinner image or status
    //AJAX request completed, so get the response
    var title=$(data).find("#Header1_headerimg").attr("alt");
    $(".ajax_response").empty().append("Error while performing AJAX request"); /* if error */

Test Code

Don’t be scared by this code (just saying). Well, this code performs an AJAX (GET) request to http://www.thedeveloper24.com/ with some example parameters (postVar1postVar2). Before initiating this AJAX request, we put a loading message in a div with class ajax_response. You can add some image too.  Upon successful AJAX request, we parse the response using success:function() and show it in the same div (with class="ajax_response").

You can use this code depending on what you are trying to do. Execute AJAX on click, or on any other event you want. Well, this is just an example to help you getting this started.

jQuery's ajax() can support some other data types too (json, html, plaintext etc). You can read the official documentation here.

Leave a Reply

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