jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery

[ad name=”AD_INBETWEEN_POST”] jQuery, the JavaScript library provides some powerful set of jQuery AJAX API’s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX. jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery.

GET Request method using jQuery

jquery-logo Load a remote page using HTTP GET request method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).

jQuery.get( url, [data], [callback], [type] )

url: (String) The URL of the page to load. data (Optional): (Map) Key/value pairs that will be sent to the server. callback (Optional): (Function) A function to be executed whenever the data is loaded successfully. type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”. e.g.
$.get( "http://some-remote-site", "{key:value}", function(data) { alert(data); }, "html" ); $.get( "http://some-remote-site", function(data) { alert(data); }, );
Code language: JavaScript (javascript)

POST Request method using jQuery

Sending post method is also very easy with jQuery. All you have to do is just to call jQuery.post () method instead of jQuery.get (). Following is the syntax of post method.

jQuery.post( url, [data], [callback], [type] )

url: (String) The URL of the page to load. data (Optional): (Map) Key/value pairs that will be sent to the server. callback (Optional): (Function) A function to be executed whenever the data is loaded successfully. type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.
$.post("test.php", { func: "getNameAndTime" }, function(data){ alert("Hello"); }, "json");
Code language: JavaScript (javascript)

Get JSON using jQuery

JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript. JQuery provides a function that can be used to make an AJAX call and get the data in JSON format. Normally the data that we get from AJAX is converted in JSON by calling eval () method of JavaScript. But the function provided by JQuery handles this internally and provides direct JSON object as output.

jQuery.getJSON( url, [data], [callback] )

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });
Code language: JavaScript (javascript)

AJAX Start/End using jQuery

While you make an AJAX call and get some data from server, it is good to show a progress bar or image to user so that (s)he knows that something is going on. Hence Loading… text is common in AJAX enabled application. What if you web application is making many AJAX calls like gmail. You may want to display a Loading… text while any of AJAX call is proceeding. To achieve this ajaxStart() and ajaxComplete() methods of jQuery can be used. ajaxStart() method registers a function handler that will be called by jQuery internally whenever an AJAX call is made. If already a request is active than the handler is not called. We can use this method to register a handler function that will display our progress bar.
$.ajaxStart(function() { $("div#loading").text("Loading..."); });
Code language: JavaScript (javascript)
In above code snippet, we used ajaxStart() method to register a function that set the innerHTML of div to Loading… Similarly ajaxComplete() method can be used to register a handler function which gets called by jQuery when an AJAX request get completed and any other active request are not in progress.
$.ajaxComplete(function() { $("div#loading").text(""); });
Code language: JavaScript (javascript)

Serialize html form using jQuery

While submitting a form using AJAX, one has to create a input string that contains the value of all the input elements on the screen. It is very difficult to create this string if your form is very big. Hence we can use jQuery’s serialize() and serializeArray() method to do so.

serialize()

Serializes a set of input elements into a string of data. Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. In order to work properly serialize requires that form fields have a name attribute. Having only an id will not work.
var str = $("form").serialize(); $("#results").text(str);
Code language: JavaScript (javascript)
In above code snippet, we created a serialize output of the form. This value can be sent to server by an AJAX call.

serializeArray()

serializeArray() does the similar job. Except it creates JSON output.
[ {name: 'firstname', value: 'Hello'}, {name: 'lastname', value: 'World'}, {name: 'alias'}, // this one was empty ]
Code language: JavaScript (javascript)
If you read this far, you should follow me on twitter here.
Get our Articles via Email. Enter your email address.

You may also like...

76 Comments

  1. BParker says:

    Excelent tutorial, direct, to the point, and in exactly the right order for developing an app!

    Thanks

  2. Comment:
    Thank u for gooda tutorial. I got lot information about ajax using the jquery…
    Keep on posting these types of good tuorials…….
    Great work…..
    All the best……

  3. soevar says:

    Good tutorial… :D

  4. Hey,

    It is a good help to me.
    It might be useful to me.

  5. You have collected the complete set, I like the way you’ve illustrated the methods,

    and from now, I’ll use jQuery Ajax API

  6. Gaurav Gupta says:

    Thanks Dear… Grt tutorials… I hv been searching for json ajax requests for a long time… gud wrk :-)

    • @Gaurav – Thanks for the good words.

  7. henrihnr says:

    hi, good tutorial. i would like to ask about ajaxStart and ajaxComplete methods. They are registered to every ajax call. How do we register each ajaxStart/ajaxComplete to each ajax call? suppose there are 2 section on screen that use ajax, each section requires Loading sign at specific position. or is there any technique to do this using jquery?

    Thanks for your attention.

  8. Indialike says:

    Very nice and useful tutorials for web designers,
    Thanks for posting.

  9. ajith says:

    good yarrrrrrrrrrrr……….

  10. Andy says:

    Great tutorial. Most tutorials get into way to many unimportant details which leaves the reader confused. This is a great way to build a foundation for using jquery to perform Ajax since I’m a jquery newb. Thanks!

    • @Andy: Thanks for the comment. I appreciate that you liked the tutorial. Feel free to bookmark/share this article.

  11. Mark says:

    Great tutorial!

  12. akhilesh says:

    thanks its really important

  13. kb says:

    its powerful tutorial for starting of Ajax with jQuery.

  14. anjali says:

    great tutorial.ur explanation is very nice and easy to understand for beginners also..

  15. Vikas Parab says:

    Please help to fix my problem. I want to use load with post method. I am writting javascript function like below:

    function test()
    {
    qString = “a:’1′,b:’2′,c:’3′
    $(“#objectID”).load(“test.php”, {qString} );
    }

    the above function gives me error.
    Instead of variable if i write function like below, then it works properly.
    $(“#objectID”).load(“test.php”, {“a:’1′,b:’2′,c:’3′} );

    Please let me know how I typecast qString.

    Thank you.
    Regards
    Vikas Parab

  16. HI Viral,
    I want to merge two row having same value for whole table for perticular column. in Java script or JQ. we develoing intarnet application for my company.

  17. Kjell says:

    Thanks this is just what we needed, excellent tutorial.

  18. A really very informative tutorial on the subject.

  19. Thank u for good tutorial…

  20. Real decent jquery/ajax tut cheers :D

  21. ricky says:

    any working demo? thnx

  22. Ramesh says:

    hi, this is nice tutorial.
    thanks

  23. Onion says:

    Thanks, this is just what I was looking for to start using AJAX. The only other think I’d have liked was a practical example of seeing all these working together, so that I could see what the ideal AJAX project should look like.

  24. Wally says:

    Thanks for the awesome tutorial. Spot on as usual. Just what i was looking for my project.

  25. Zuallauz says:

    Thanks, good info. However passing “{key:value}” into the $.get method doesn’t work. You actually need to pass the values in as {key:value} without double quotes. E.g. {id: 1, name: “Bob”}

  26. web design says:

    great tutorial….jquery is really my lovely library…thanks for sharing this.

  27. shrikant says:

    nice tutorial
    easy 2 understand,with easy words…thnks grt work

  28. javaeschool says:

    Thx for this very helpful tutorial..
    It helped me in my project…:)

  29. Deva Karthik says:

    Very Helpful!

  30. girssss says:

    good ……

  31. Irfan says:

    outstanding article

  32. it really good article i am using your technique in our site

  33. Richard says:

    Looks nice. I will try it out to give you a feedback soon.

  34. Richard says:

    Easy to read, but a show about how the whole things work together under a simplified real setting would make it better.

  35. ahmet says:

    thanks mate :)

  36. Thank you so much for such a nice article.
    i liked it very much.
    Thank you for sharing. Mark

  37. Virendra says:

    Bloody Awesome..

    But I don’t prefer jQuery.post() or jQuery.get() method to do an ajax call as they don’t support error handling.

    http://jquerybyexample.blogspot.com/2011/11/avoid-jquerypost-use-jqueryajax.html

    I prefer jQuery.ajax() as it supports error handling as well.

  38. Arul says:

    how to get local server get json values simple example please help me.
    example if local server path Get JSON url and data.

  39. Arvind says:

    good tutorial but i use $.ajax() it is simple too…….

  40. Golak Jena says:

    Very good tutorial….
    It’s very needful….
    Thanks

  41. psharp says:

    BEWARE: This technique won’t work except for getting json.
    jquery documentation explains here (read “Additional Notes” at bottom) :
    http://api.jquery.com/jQuery.get/

    You can spend hours chasing errors if you don’t notice this detail!!!

    So VP, please at least include the warning

  42. snehal says:

    nice 1..

  43. steveen says:

    Thanks Man!, its a great tutorial!

  44. rajiv says:

    This is a nice way of explanation of the topic . I need a help from you to manage JPEG on Prestashop.
    Kindly help me out.

  45. Svetlana says:

    Thank you for a great article and useful tips, guys!

  46. Harry says:

    thanks alot..its of great help towards my project.

  47. Rajesh says:

    Thanks

  48. manju says:

    hi. good one… If you have given complete code for posting value and and accessing the same in single code snippet, then it would be still more easier for us… but its nice…

  49. jaswanth says:

    Good tutorial…!!

  50. Manish says:

    nice and useful. Good job !!!!!!!!

  51. farhaan says:

    in ajax call method we can use callback what of argument callback method has

  52. Ya I agree with you “farhaan” that in Ajax call method, we can use a callback method.

  53. wecode says:

    good work! found it very helpful. Thanks for sharing.

  54. Free classifieds says:

    Worked, Thanks for sharing

  55. Hunta says:

    The only person I have found in 5 hours crawling the net who thought to mention you have to use the name attribute when passing form data. Thank you, you saved the day.

  56. Hi Viral,

    Thanks for sharing..! Just want to understand a bit all these codes as shown in above examples need to call in the $( document ).ready() or we call it as it is without $( document ).ready() and can you please provide me complete source code on the same. i really lik the article especially the Get JSON using jQuery example. Keep posting ..Thanks

    • Pankaj says:

      $.getJSON( url , params , callback ) 


      Load JSON data using an HTTP GET request.
      Parameters
      url: ( String ): The URL of the page to load.
      params: ( Map ): (optional) Key/value pairs that will be sent to the server.
      callback: ( Function ): A function to be executed whenever the data is loaded.
      Returns
      XMLHttpRequest
      Example

      $.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });  


      Example

      $.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); } );  

  57. Amit Singh says:

    hi help me ,,

    i want to design such application that without page refresh if any new record inserting in data base 1 notification should be come loke fb , and after click on notification all values in that database releted to that notofication should be show …

    can anyone help ????

    thanks in advance !!!!!!!

  58. Raju says:

    Nice one.

  59. Satya says:

    Hi,
    I need a code for pagination using ajax .I have apply it to already existing code where it is not done using pagination
    TIA

  60. Mohamed Haniffa Ahamed says:

    good

  61. Harish says:

    Am currently using Struts2 & Hibernate for a web project.Which toolkit is good for Ajax implementation?(Need for auto-populating values from Database).If so ? any links to similar implementation?

  62. BookNabber says:

    very simple example to learn call back.

  63. Habeeb Sk says:

    Simple Example fro Ajax setup () method

    $(“button”).click(function(){
    $.ajaxSetup({url: “demo_ajax_load.txt”, success: function(result){
    $(“div”).html(result);}});
    $.ajax();
    });

  64. Rav Smith says:

    Thanks a lot Patel for sharing such a great tutorial. I am not enough familiar with AJAX your post clear some of my doughts,

  65. Bhavesh Parmar says:

    Good article! The post provides very important tips about AJAX. The post will be helpful for all developers and designers like me. Thanks for sharing.

  66. Hakuna Matata says:

    Interesting and quite helpful too …great jquery.

  67. Divakar says:

    very good article about JQurey and provides a lot of information about it. thanks for the article it was very helpful for the beginners

  68. freya riki says:

    The way of your article presentation is very effective and very easy to understand. Share more like this.

  69. Max Rusel says:

    Thanks for sharing this knowledgeable blog with us, truly a great informative site. It is very helpful for us.

  70. java devolpment company says:

    as per my experince
    Top 10 JavaScript Frameworks 2020. Every year, many JavaScript libraries and frameworks enter the market. Some of them gain a raised popularity and picked by app development companies for creating futuristic applications, while others remain behind the curtains or go extinct.

  71. good work! found it very helpful. Thank you so much for such a nice article.

  72. The post was excellent and good.

Leave a Reply

Your email address will not be published. Required fields are marked *