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.

36 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
  2. thanks for sharing...
    www.7eleventech.com

    ReplyDelete
  3. Thanks for sharing this informative blog. Recently I did Digital Marketing Training in Chennai at a leading digital marketing company. It's really useful for me to make a bright career. To know more details about this course please visit FITA.

    ReplyDelete
  4. Hi, Thanks for sharing this valuable blog.I was really impressed by reading this blog. I did HTML Training in Chennai at reputed HTML5 Training Institutes in Chennai. This is reslly useful for me to make a bright future in designing field.

    ReplyDelete
  5. SEO Training institute Chennai

    Your information is really useful for me.Thanks for sharing such a valuable information. If anyone wants to get SEO Course in Chennai visit FITA Academy located at Chennai. Rated as No.1 SEO Training Center in Chennai.

    SEO Training in Chennai

    ReplyDelete
  6. The information you posted here is useful to make my career better keep updates..Recently I did oracle certification course at a leading academy. Suppose if anyone want to become an oracle certified professional reach FITA Oracle Training Institutes in Chennai, which offers Best Oracle Training in Chennai with years of experienced professionals.

    ReplyDelete
  7. Thanks for sharing this niche useful informative post to our knowledge, Actually SAP is ERP software that can be used in many companies for their day to day business activities it has great scope in future...
    sap training in Chennai | SAP ABAP Training In Chennai | SAP SD Training In Chennai

    ReplyDelete
  8. Thank you so much for sharing this informative blog. Your technical information is really useful for me. Keep update your blog.

    Regards..

    PHP Training in Chennai

    ReplyDelete
  9. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Regards,

    Best Informatica Training In Chennai | Informatica training in chennai

    ReplyDelete
  10. Thanks for sharing this information. Java is one of the popular object oriented programming language used for many of the multinational corporation. So learning Best Java Training in Chennai is really helpful to make a bright future.

    ReplyDelete
  11. This was so useful and informative. The article helped me to learn something new. By web designing course in chennai

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Very much useful information which helped me gain something knowledgeable. By vegetarian restaurant

    ReplyDelete

  14. The information you have given here is truly helpful to me. CCNA- It’s a certification program based on routing & switching for starting level network engineers that helps improve your investment in knowledge of networking & increase the value of employer’s network, if you want to take ccna course in Chennai get into FITA, thanks for sharing
    Regards,
    ccna course in Chennai|ccna training in Chennai

    ReplyDelete
  15. This was so useful and informative. The article helped me to learn something new. By industrial electrical contractors in Chennai

    ReplyDelete
  16. Nice to learn something jquery ajax functions from this article. You can refer some digital marketing institute here.

    ReplyDelete
  17. Thanks for sharing use interview questions on .Net technology. While preparing for my job interview, your article helped me a lot to sharpen my skills and do well in my interview. one of trainer from leading dot net training institutes in Chennai suggests me about your site.

    For info : Dot Net Training in Chennai

    ReplyDelete
  18. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    online marketing courses in chennai

    ReplyDelete
  19. Thanks for sharing this information. Java is one of the popular object oriented programming language used for many of the multinational corporation.
    seo training in Chennai

    ReplyDelete
  20. Thank you for this wonderful tutorial. I happened to learn some few things from it. So once again thanks.

    digital marketing courses

    ReplyDelete
  21. Very useful article. Helps students to easily get placed in interviews. keep posting more such articles on interview question and answers.
    Web designing course in Chennai | Web designing course in Chennai

    ReplyDelete
  22. This was so useful and informative. The article helped me to learn something new...
    Oracle Training in chennai

    ReplyDelete
  23. The information you have given here is truly helpful to me..
    Oracle Training in Chennai

    ReplyDelete
  24. Informatica Training in chennai
    The information you posted here is useful to make my career better keep updates..

    ReplyDelete
  25. Your information is really useful for me.Thanks for sharing such a valuable information..
    Hadoop Training in Chennai

    ReplyDelete
  26. QTP Training in Chennai
    Hi, Thanks for sharing this valuable blog.I was really impressed by reading this blog..

    ReplyDelete
  27. SAS Training in Chennai
    Your information is really useful for me.Thanks for sharing such a valuable information. If anyone wants to get SAS Course in Chennai visit Greens Technology located at Chennai...

    ReplyDelete
  28. Green Technologies In Chennai
    Green Technologies In Chennai
    I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..

    ReplyDelete
  29. nice to read about ajax and oracle learn advanced oracle product in weblogic server
    learn more oracle

    ReplyDelete
  30. Thanks for sharing this useful post; Actually Salesforce crm cloud application provides special cloud computing tools for your client management problems. It’s a fresh technology in IT industries for the business management.
    Regards,
    Salesforce training chennai

    ReplyDelete