Please navigate to the bottom of the page for Table of Contents

Friday, June 3, 2011

jQuery AJAX functions part 2–get(), post(), getScript() and getJSON()

In this second post we will discuss some other jQuery AJAX functions. First of all, not that these are jQuery functions (they operate directly on jQuery or $ and not on jQuery objects). From an interview perspective, you may or may not be directly asked about these functions. It might be disguised as a different question. For example, How can you send data back to the server asynchronously? How do you get and parse JSON data from the server? And so on.

get(), post()

jQuery get() and post() can be used to fetch the content of a web page, pass in optional data and also optionally invoke a callback. They are very similar in their signature to the load() method we discussed previously. In addition to the data and callback, both these methods also provide an optional 4th argument – the datatype is used to specify the type of data you are requesting back and is used before your callback is executed.

As their names imply, get() uses the HTTP GET protocol and post() uses the POST protocol.

// Request text and display it in an alert dialog
jQuery.get("errors.html", alert);


The official jQuery API page on get() at http://api.jquery.com/jQuery.get/ lists some great examples some of which are shown below:


Example: Request the test.php page, but ignore the return results.


$.get("test.php");


Example: Request the test.php page and send some additional data along (while still ignoring the return results).


$.get("test.php", { name: "John", time: "2pm" } );


Example: pass arrays of data to the server (while still ignoring the return results).


$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );


The post() calls are pretty much the same as get(). A few examples from the official jQuery API page are shown below.


Example: Request the test.php page, but ignore the return results.


$.post("test.php");


Example: Request the test.php page and send some additional data along (while still ignoring the return results).


$.post("test.php", { name: "John", time: "2pm" } );


Example: pass arrays of data to the server (while still ignoring the return results).


$.post("test.php", { 'choices[]': ["Jon", "Susan"] });


Example: send form data using ajax requests


$.post("test.php", $("#testform").serialize());


 


jQuery getScript() function


The jQuery.getScript() function takes the URL of a JavaScript file to load and then asynchronously loads and executes that code in the global scope. A key point to note is that it can work for both same-domain and cross-domain scripts.


// Dynamically load a script from some other server
jQuery.getScript("http://contoso.com/js/helpers.js");

The getScript() function takes an optional second parameter which is a callback to be executed on success.

// Load helpers and use it once it loads
jQuery.getScript("js/jquery.my.helpers.js", function() {
$('div').help(); // Use it
});



Note that the callback is only executed when the request succeeds. If you want to handle the error case, you will need to use the big brother – the ajax() call.


jQuery getJSON() function


Our final function is getJSON(). This is very similar to getScript() but instead of executing the contents after fetching (as is the case with getScript(), getJSON() parses it as JSON (using the parseJSON() under the covers) and then passes the resultant JSON to the callback. You can optionally send data back to the server as the second argument.


Again, to borrow an example from the official jQuery API page on getJSON() function - http://api.jquery.com/jQuery.getJSON/, the code snippet below uses the following JSON structure to loop through the requested data, builds an unordered list, and appends it to the body.


{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}



$.getJSON('ajax/test.json', function(data) {
var items = [];

$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});

$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});

All these functions are shorthand AJAX functions and call also be invoked via the .ajax() call.

2 comments:

  1. Recently I had caching issues with sending jQuery Ajax requests to server and I had to add a random number to the URL by using javascript.Same is the case with any framework sending ajax request.

    ReplyDelete
    Replies
    1. This happens only with get requests. We can either use post request or ajaxSetup with cache as false before executing the request.

      Delete