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.

73 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
  31. If wants to get real time Oracle Training visit this blog They give professional and job oriented training for all students.To make it easier for you Greens Technologies trained as visualizing all the real-world Application and how to implement in Archiecture trained with expert trainners guide may you want.. Start brightening your career with us Green Technologies In Chennai

    ReplyDelete
  32. Nice site....Please refer this site also if Our vision succes!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Realtime methodologies Green Technologies In Chennai

    ReplyDelete
  33. I also wanted to share few links related to sas training Check this sitete.if share indepth sas training.Go here if you’re looking for information on sas training. SAS Training in Chennai

    ReplyDelete
  34. This site has very useful inputs related to qtp.This page lists down detailed and information about QTP for beginners as well as experienced users of QTP. If you are a beginner, it is advised that you go through the one after the other as mentioned in the list. So let’s get started… QTP Training in Chennai

    ReplyDelete
  35. Hi. Nice post. I am wondering if it is possible.Actually pega software that can be used in many companies for their day to day business activities it has great scope in future.if suggest best coaching center visit Pega Training in Chennai

    ReplyDelete
  36. fantastic presentation of informatica..if sharinng this session will describe near real-time architectures for accelerating the delivery of data to critical analytics and customer service applications in real world once again i want to share this sites Informatica Training in chennai

    ReplyDelete
  37. Hey, nice site you have here!We provide world-class Oracle certification and placement training course as i wondered Keep up the excellent work experience!Please visit Greens Technologies located at Chennai Adyar Oracle Training in chennai

    ReplyDelete
  38. if share valuable information about hadoop training courses, certification, online resources, and private training for Developers, Administrators, and Data Analysts may visit Hadoop Training in Chennai

    ReplyDelete
  39. if share valuable information about hadoop training courses, certification, online resources, and private training for Developers, Administrators, and Data Analysts may visit Hadoop Training in Chennai

    ReplyDelete
  40. Hey, nice site you have here!We provide world-class Oracle certification and placement training course as i wondered Keep up the excellent work experience!Please visit Greens Technologies located at Chennai Adyar Oracle Training in chennai

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

    ReplyDelete
  42. I would recommend the Qlikview course to anyone interested in learning Business Intelligence .Absolutely professional and engaging training sessions helped me to appreciate and understand the technology better. thank you very much if our dedicated efforts and valuable insights which made it easy for me to understand the concepts taught and more ... qlikview Training in chennai

    ReplyDelete
  43. Thanks for sharing this informative blog .To make it easier for you Greens Techonologies at Chennai is visualizing all the materials about (OBIEE).SO lets Start brightening your future.and using modeling tools how to prepare and build objects and metadata to be used in reports and more trained itself visit Obiee Training in chennai

    ReplyDelete
  44. Hello Admin, thank you for enlightening us with your knowledge sharing. PHP has become an inevitable part of web development, and with proper PHP training center in Chennai, one can have a strong career in the web development field. We from Fita provide PHP training center in Chennai with the best facilitation. Any aspiring students can join us for the best PHP training center in Chennai.

    ReplyDelete
  45. Hello Admin, thank you for enlightening us with your knowledge sharing. PHP has become an inevitable part of web development, and with proper PHP training center in Chennai, one can have a strong career in the web development field. We from Fita provide PHP training center in Chennai with the best facilitation. Any aspiring students can join us for the best PHP training center in Chennai.

    ReplyDelete
  46. Great article! and thanks for your informative sharing..its useful for me...
    office interior designers in Chennai

    ReplyDelete
  47. Thanks for the article. It has given me so much information that I shared with my students in the class. Come up with more such articles.
    Shashaa
    Dot Net training Chennai | Dot Net training Chennai | Dot Net training Chennai

    ReplyDelete
  48. Thank you so much for providing us such an informative article.

    ReplyDelete
  49. interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts,Thanks a million once again, Regards,servicenow training in hyderabad ,splunk training in hyderabad

    ReplyDelete
  50. Hai if our training additional way as (IT) trained as individual,you will be able to understand other applications more quickly and continue to build your skll set
    which will assist you in getting hi-tech industry jobs as possible in future courese of action..
    visit this blog webMethods-training in chennai



    ReplyDelete
  51. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    QTP Training in Chennai

    ReplyDelete
  52. Hi Admin,
    Your website is totally awesome and loaded with various informative posts on web design and development. Keep on updating your blog. Web Design Training | Web designing course in Chennai

    ReplyDelete
  53. That is a brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at our dot net training institute in Chennai. Thanks a lot. Keep writing more on dot net course in Chennai, would love to follow your posts and refer to others in dot net training institutes in Chennai.

    ReplyDelete
  54. Hello admin, thank you for your informative post on hadoop training in Chennai. It helped a lot in training my students during our hadoop training Chennai sessions. We at Fita, provide big data training in Chennai for students who are interested in choosing a career in big data.

    ReplyDelete
  55. Haryana HSSC Steno Typist Recruitment 2016

    This is very interesting, Really great you are a very skilled blogger.................

    ReplyDelete
  56. Great info. Lucky me I discovered your site by chance. I have saved it for later!
    SAP APO Online Training

    ReplyDelete
  57. hai have a good day.....
    i think this is useful for all of us..i am really enjoying when i reading.thanks for updating this informative article..
    i am waiting for your upcoming article..i hope it will be come soon as possible...http://sonymobileservicecenterinchennai.in/

    ReplyDelete
  58. Hi, I am really happy to found such a helpful and fascinating post that is written in well manner. Thanks for sharing such an informative post.
    Regards..
    QTP Training in Chennai

    ReplyDelete
  59. Hi Dude,
    Awesome Post!!! With unique content, I really get reading interest when I am following your article, I hope I ll help many of them who looking this pretty information.
    Regards,

    Python Training in Chennai|Python Training Institutes in Chennai|python training chennai|FITA Academy reviews

    ReplyDelete
  60. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Regards,

    Informatica training in chennai|Best Informatica Training In Chennai|SAS Training in Chennai

    ReplyDelete
  61. Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
    Informatica Training In Chennai
    Hadoop Training In Chennai
    Oracle Training In Chennai
    SAS Training In Chennai

    ReplyDelete
  62. Best iOS Training Institute In Chennai It’s too informative blog and I am getting conglomerations of info’s about Oracle interview questions and answer .Thanks for sharing, I would like to see your updates regularly so keep blogging.

    ReplyDelete
  63. I have read this content it is very nice with unique information and keep updating us.
    Digital Marketing Training in Chennai | digital marketing course in Chennai | FITA Velachery

    ReplyDelete