Saturday, March 30, 2013

5 Ways to Make Ajax Calls with jQuery

What is AJAX

 AJAX stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request, it’s the same thing. Don’t be afraid of this jargon; AJAX is not rocket science.

The key to AJAX’s concept is “asynchronous”. This means something happens to the page after it’s loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

For static content, we may want the response cached. But for dynamic content, which can change in a second’s time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So we’d better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:

  1. $.ajaxSetup ({  
  2.     cache: false  
  3. }); 
  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

1. load(): Load HTML From a Remote URL and Inject it into the DOM

    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='img/load.gif' alt='loading...' />";
   
//    load() functions
    var loadUrl = "ajax/load.php";
    $("#load_basic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

2. $.getJSON(): Retrieve JSON from a Remote Location

//    $.getJSON()
    var jsonUrl = "ajax/json.php";
    $("#getJSONForm").submit(function(){
        var q = $("#q").val();
        if (q.length == 0) {
            $("#q").focus();
        } else {
            $("#result").html(ajax_load);
            $.getJSON(
                jsonUrl,
                {q: q},
                function(json) {
                    var result = "Language code is \"<strong>" + json.responseData.language + "\"";
                    $("#result").html(result);
                }
            );
        }
        return false;
    });

 

3. $.getScript(): Load JavaScript from a Remote Location

//    $.getScript()
    var scriptUrl = "ajax/script.php";
    $("#getScript").click(function(){
        $("#result").html(ajax_load);
        $.getScript(scriptUrl, function(){
            $("#result").html("");
        });
    });

4. $.get(): Make GET Requests

 //    $.get()
    $("#get").click(function(){
        $("#result").html(ajax_load);
        $.get(
            loadUrl,
            {language: "php", version: 5},
            function(responseText){
                $("#result").html(responseText);
            },
            "html"
        );
    });

5. $.post(): Make POST Requests

//    $.post()
    $("#post").click(function(){
        $("#result").html(ajax_load);
        $.post(
            loadUrl,
            {language: "php", version: 5},
            function(responseText){
                $("#result").html(responseText);
            },
            "html"
        );
    });

Finally… $.ajax():
Up to this point, we’ve examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.