jQuery ajax method
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
All the other wrapper AJAX methods like get(), post() internally use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
Simplified syntax
jQuery.ajax( url [, settings ] )
or
$.ajax( url [, settings ] )
Lets see some examples of the jQuery ajax method.
jQuery ajax with JSON
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> var url = 'https://api.github.com/users/topjavatutorial/repos'; $.ajax({ url: url, success: function(data) { document.getElementById("ajaxdata").innerHTML = data[0].html_url; } }); </script> </head> <body> <div id="ajaxdata">This text will be replaced with AJAX response</div> </body> </html>
jQuery ajax with XML
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> var url='https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'; $.ajax({ url: url, success: function(xml) { document.getElementById("ajaxdata").innerHTML = $(xml).find('formatted_address').text(); } }); </script> </head> <body> <div id='ajaxdata'> Fetching address from Google map </div> </body> </html>
ajax method parameters
The ajax method can accept many different parameters, and can POST data to or GET data from a server.
Here is syntax for some more commonly used parameters :
$.ajax({
url: "abc.html",
type: "GET",
dataType : "text",
success: function(text) {...},
error: function(xhr) {...},
complete: function() {...}
});
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> var url='https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'; $.ajax({ url: url, type: "GET", dataType : "xml", success: function(xml) { document.getElementById("ajaxdata").innerHTML = $(xml).find('formatted_address').text(); }, error:function(xhr){ //alert("Error : " + xhr.statusText); document.getElementById("ajaxdata").innerHTML = xhr.statusTextxhr.statusText; }, complete:function(){ //alert("AJAX request completed"); document.getElementById("ajaxdata").innerHTML += "<p>AJAX request completed</p>"; } }); </script> </head> <body> <h3>Address</h3> <p id="ajaxdata"> Fetching address from Google map </p> </body> </html>
Shorthand AJAX methods
The jQuery ajax method provides fine-grained control over the AJAX call.
jQuery also provides shorthand AJAX methods like load(), get() and post().
We will cover more on these methods in the next article.
References
http://api.jquery.com/jQuery.ajax/
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post