All jQuery AJAX Methods (Explained With Examples)
load() method in jQuery AJAX
JQuery AJAX’s load()
method is a simple but effective approach. Using the load method, you can obtain data from servers and store it in the elements you specify.
Syntax for load method in jQuery AJAX
$(selector).load(URL,data,callback);
The URL you want to load is specified by the required URL parameter. The data parameter, which is optional, specifies a set of query string key/value pairs to send with the request.
The optional callback parameter specifies the function's name that will run after the load()
method has finished.
The following is the content of our "demo test.txt" file:
jQuery Tutorial for Beginners!!!
Let’s learn jQuery practically.
The content of the file "demo test.txt" is loaded into a specific
Example of jQuery AJAX load method
$("#div1").load("demo_test.txt");
A jQuery selector can also be added to the URL parameter.
In the following example, the content of the element with id="p1" from the file "demo test.txt" is imported into a specific div> element:
Example
$("#div1").load("demo_test.txt #p1");
When the load()
method is finished, the optional callback parameter specifies a callback function to run. The parameters of the callback function can be varied:
If the call is successful, responseTxt contains the resultant content.
-
statusTxt: Contains the call's status.
The XMLHttpRequest object is stored in the xhr variable.
After the load()
function completes, the following example shows an alert box. The message "External content loaded successfully!" is displayed if the load()
method succeeds.
jQuery AJAX get() and post() Methods
With an HTTP GET or POST request, the jQuery get()
and post()
methods are used to request data from the server.
GET vs POST in HTTP Requests
Two generally used techniques for a request-response between a client and a server are GET and POST.
-
GET: Gets information from a specific resource.
-
POST: Sends data to a specified resource to be processed.
The role of both GET and POST is to retrieve information from severs. However, GET may return the already-cahced data, but POST will not cache data. Instead, the POST method sends data with a request.
jQuery AJAX $.get() Method
With an HTTP GET request, the $.get()
method requests data from the server.
Syntax of $.get
method in AJAX jQuery
$.get(URL,callback);
The required URL parameter specifies the requested URL.
If the request succeeds, the optional callback parameter specifies the name of a function that will be executed.
The $.get()
method is used in the following example to retrieve data from a server file:
jQuery AJAX $.get
example
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of $.get
is the URL we wish to retrieve ("demo test. asp").
A callback function is the second parameter. The first callback parameter contains the content of the requested page, while the second callback parameter contains the request's status.
Here's what the ASP file ("demo test. asp") looks like:
<%
response.write("This is some text from an external ASP file.")
%>
AJAX $.post() Method in jQuery
This $.post()
method uses an HTTP POST request to get data from the server.
Syntax for $.post
method in AJAX jQuery
$.post(URL,data,callback);
The required URL parameter specifies the requested URL.The optional data parameter specifies additional information to send with the request.
If the request succeeds, the optional callback parameter specifies the name of a function that will be executed.
The $.post()
method is used in the following example to send data along with the request:
Example of AJAX jQuery post method
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The URL we want to obtain ("demo test.asp") is the first parameter of $.get ()
. Then we provide some information to send with the request (name and city).
"demo test post.asp" contains an ASP script that reads the parameters, processes them, and returns a result.
A callback function is the third parameter. The first callback parameter contains the content of the requested page, while the second callback parameter contains the request's status.
This is how the ASP file ("demo test post. asp") looks:
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>
jQuery.ajaxPrefilter Method
jQuery.ajaxPrefilter( [dataTypes ], handler )Returns: undefined
Handle custom Ajax options or change existing options before each request is sent and processed by $.ajax ()
.
Type: String dataTypes
An optional string containing one or more dataTypes handlers separated by spaces.
Function: Type (PlainObject options, PlainObject originalOptions, jqXHR jqXHR)
A handler for setting default values for Ajax requests in the future. A typical $.ajaxPrefilter()
registration looks like this:
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
// Modify options, control originalOptions, store jqXHR, etc
});
When custom options must be handled, pre filters are ideal. If the custom abortOnRetry option is set to true in the following code, a call to $.ajax()
will automatically abort a request to the same URL:
var currentRequests = {};
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.abortOnRetry ) {
if ( currentRequests[ options.url ] ) {
currentRequests[ options.url ].abort();
}
currentRequests[ options.url ] = jqXHR;
}
});
jQuery AJAX get() Method
The $.get()
method uses an HTTP GET request to retrieve data from the server.
You'll get the following answer if you make an HTTP GET call to a page:
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
jQuery ajaxSetup() Method
The ajaxSetup()
method establishes default values for AJAX requests in the future.
Syntax for ajaxSetup method in jQuery
$.ajaxSetup({name:value, name:value, ... })
Example of jQuery ajaxSetup method
For all AJAX requests, set the default URL and success function:
$("button").click(function(){
$.ajaxSetup({url: "demo_ajax_load.txt", success: function(result){
$("div").html(result);}});
$.ajax();
});
jQuery.ajaxTransport() method
Transport is an object with two methods: send an abort, used by $.ajax()
to issue requests internally. When prefilters and converters are insufficient, transport is the most advanced way to enhance $.ajax()
.
Transports cannot be registered directly because each request requires its transport object instance. As a result, instead of providing a function that returns a transport, you should provide a function that returns a transport.
$.ajaxTransport
is used to register transport factories (). An example of a typical registration:
$.ajaxTransport( dataType, function( options, originalOptions, jqXHR ) {
if( /* transportCanHandleRequest */ ) {
return {
send: function( headers, completeCallback ) {
// Send code
},
abort: function() {
// Abort code
}
};
}
});
jQuery getJSON() Method
Using an AJAX HTTP GET request, the getJSON()
method retrieves JSON data.
Syntax for getJSON method in jQuery
$(selector).getJSON(url,data,success(data,status,xhr))
Example of jQuery getJSON method
Using an AJAX request, get JSON data and output the result:
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
jQuery getScript() Method
Using an AJAX HTTP GET request, the getScript()
method retrieves and executes a JavaScript.
Syntax for getScript method in jQuery
$(selector).getScript(url,success(response,status))
Example of jQuery getScript method
Using an AJAX request, get and run a JavaScript:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
jQuery param() Method
The param()
method in jQuery converts an array or object into a serialised representation.
When making an AJAX request, the serialised values can be used in the URL query string.
Syntax for jQuery param method
$.param(object,trad)
Example of param method in jQuery AJAX
Output the serialised object's result:
$("button").click(function(){
$("div").text($.param(personObj));
});
jQuery post() Method
The $.post()
method uses an HTTP POST request to retrieve data from the server.
Syntax for post method in jQuery
$(selector).post(URL,data,function(data,status,xhr),dataType)
Example 1
Using an HTTP POST request, retrieve data from the server:
$("button").click(function(){
$.post("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
Example 2
Using an AJAX POST request, change the text of a div> element:
$("input").keyup(function(){
var txt = $("input").val();
$.post("demo_ajax_gethint.asp", {suggest: txt}, function(result){
$("span").html(result);
});
});
jQuery ajaxComplete() Method
When an AJAX request completes, the ajaxComplete()
method specifies a function to run. This method should only be attached to a document as of jQuery version 1.8.
Unlike ajax success()
, functions specified with the ajaxComplete()
method, unlike ajax success()
, will run when the request is completed, even if it is unsuccessful.
Syntax for ajaxComplete method in jQuery
$(document).ajaxComplete(function(event,xhr,options))
Example of ajaxComplete method
While an AJAX request is being processed, display a "loading"
indicator image:
$(document).ajaxStart(function(){
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
jQuery ajaxError() Method
When an AJAX request fails, the ajax error()
method specifies a function to run. This method should only be attached to a document as of jQuery version 1.8.
Syntax for ajaxError method in jQuery
$(document).ajaxError(function(event,xhr,options,exc))
Example of ajaxError method
When an AJAX request fails, display an alert box:
$(document).ajaxError(function(){
alert("An error occurred!");
});
jQuery ajaxSend() Method
The ajaxSend()
method defines a function to perform when an AJAX request is ready to be submitted. This method should only be attached to a document as of jQuery version 1.8.
Syntax for ajaxSend method in jQuery
$(document).ajaxSend(function(event,xhr,options))
Example of jQuery ajaxSend method
Sent an AJAX request, change the content of a
$(document).ajaxSend(function(e, xhr, opt){
$("div").append("
Requesting: " + opt.url + "
");
});
jQuery ajaxStart() Method
When an AJAX request is initiated, the ajaxStart()
method specifies a function to be executed. This method should only be attached to a document as of jQuery version 1.8.
Syntax of ajaxStart method
$(document).ajaxStart(function())
Example of ajaxStart method in jQuery
When an AJAX request begins, display a "loading"
indicator image:
$(document).ajaxStart(function(){
$(this).html("");
});
jQuery ajaxStop() Method
When ALL AJAX requests have been completed, the ajaxStop()
method calls a function. When an AJAX request is finished, jQuery checks to see if any other AJAX requests are pending. If no further requests are pending, the function specified with the ajaxStop()
method will be executed.
Note: This method should only be attached to a document as of jQuery version 1.8.
Syntax for ajaxStop method
$(document).ajaxStop(function())
Example of ajaxStop method in jQuery
When all AJAX requests have been completed, display an alert box:
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
jQuery ajaxSuccess() Method
The ajaxSuccess()
method defines a function to perform when an AJAX request is successful.
Note: This method should only be attached to a document as of jQuery version 1.8.
Syntax for ajaxSuccess method in jQuery
$(document).ajaxSuccess(function(event,xhr,options))
Example of jQuery ajaxSuccess method
When an AJAX request is successfully completed, an alert box is triggered:
$(document).ajaxSuccess(function(){
alert("AJAX request successfully completed");
});
jQuery serialize() Method
The serialise()
method creates a URL encoded text string by encoding the form values.
This method is generally used for creation of text strings in typical URL-encoded notation. It allows you to select one or multiple form values/elements like ,
Syntax for serialize method in jQuery
$(selector).serialize()
Example of jQuery AJAX serialize method
Output the serialised form values' result:
$("button").click(function(){
$("div").text($("form").serialize());
});
jQuery serializeArray() Method
By serialising form values, the serializeArray()
function generates an array of objects (name and value).
You can select one or multiple form values/elements like ,
Syntax of serializeArray in jQuery
$(selector).serializeArray()
Example of jQuery AJAX serializeArray
Output the result of serialising form values as arrays:
$("button").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
});
});