Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Sunday, November 9, 2014

How to Load AJAX Content with jQuery


Couch ModePrint It

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.




The Basic Usage


$.ajax({
  url: "http://www.thedeveloper24.com",
  success:function(data){
    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


$.ajax({
  url: "http://www.thedeveloper24.com/",
  type: "GET",
  data: { postVar1: 'theValue1', postVar2: 'theValue2' }, /* the get parameters to pass */
  beforeSend:function(){
    //show loading spinner image or status
    $(".ajax_response").empty().append("<i>Loading...</i>");
  },
  success:function(data){
    //AJAX request completed, so get the response
    //alert(data);
    $(".ajax_response").empty();
    var title=$(data).find("#Header1_headerimg").attr("alt");
    $(".ajax_response").append(title);
  },
  error:function(){
    $(".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 (postVar1, postVar2). 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.

Some loading spinner images: Ajaxload

Let me know how you use AJAX :)

:D
:)
:[
;)
:D
:O
(6)
(A)
:'(
:|
:o)
8)
(K)
(M)