jQuery Basic

jQuery Home jQuery Introduction jQuery Getting Started jQuery Syntax jQuery Selectors jQuery Events

jQuery Effects

jQuery Show/Hide jQuery Fade jQuery Slide jQuery Animation jQuery Stop jQuery Chaining jQuery Callback

jQuery manipulation

jQuery Get/Set jQuery Insert jQuery Remove jQuery CSS Classes jQuery Style Properties jQuery Dimensions

jQuery advanced

jQuery Traversing jQuery Ancestors jQuery Descendants jQuery Siblings jQuery Filtering jQuery Ajax jQuery Load jQuery Get/Post jQuery No-Conflict

jQuery Exercises

jQuery Practice Examples jQuery Quiz

jQuery References

jQuery Overview jQuery Selectors jQuery Events jQuery Effects jQuery HTML/CSS jQuery Traversing jQuery AJAX jQuery Misc jQuery Properties

jQuery AJAX Methods

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.

The following table lists all the jQuery AJAX methods

Method Description
$.ajax() Performs an async AJAX request
$.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup() Sets the default values for future AJAX requests
$.ajaxTransport() Creates an object that handles the actual transmission of Ajax data
$.get() Loads data from a server using an AJAX HTTP GET request
$.getJSON() Loads JSON-encoded data from a server using a HTTP GET request
$.parseJSON() Deprecated in version 3.0, use JSON.parse() instead. Takes a well-formed JSON string and returns the resulting JavaScript value
$.getScript() Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param() Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post() Loads data from a server using an AJAX HTTP POST request
ajaxComplete() Specifies a function to run when the AJAX request completes
ajaxError() Specifies a function to run when the AJAX request completes with an error
ajaxSend() Specifies a function to run before the AJAX request is sent
ajaxStart() Specifies a function to run when the first AJAX request begins
ajaxStop() Specifies a function to run when all AJAX requests have completed
ajaxSuccess() Specifies a function to run when an AJAX request completes successfully
load() Loads data from a server and puts the returned data into the selected element
serialize() Encodes a set of form elements as a string for submission
serializeArray() Encodes a set of form elements as an array of names and values

jQuery ajax() Method

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

Syntax:

$.ajax({name:value, name:value, ... })

The parameters specifies one or more name/value pairs for the AJAX request. As in the table below...

Name Value/Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions)
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

Example

Change the text of a <div> element using an AJAX request:

$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    $("#div1").html(result);
  }});
});
Try it Yourself

jQuery ajaxSetup() Method

The ajaxSetup() method use to sets the default values for future AJAX requests

Syntax:

$.ajaxSetup({name:value, name:value, ... })

The parameters specifies the settings for AJAX requests with one or more name/value pairs. As in the table below...

Name Value/Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions)
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

Example

Set the default URL and success function for all AJAX requests

$("button").click(function(){
  $.ajaxSetup({url: "demo_ajax_load.txt", success: function(result){
    $("div").html(result);}});
  $.ajax();
});
Try it Yourself

jQuery get() Method

The $.get() method loads data from the server using a HTTP GET request

Syntax:

$.get(URL,data,function(data,status,xhr),dataType)

Examples:

Request "test.php", but ignore return results:

$.get("test.php");

Request "test.php" and send some additional data along with the request (ignore return results):

$.get("test.php", { name:"Donald", town:"Ducktown" });

Request "test.php" and pass arrays of data to the server (ignore return results)

$.get("test.php", { 'colors[]' : ["Red", "Green", "Blue"] });

Request "test.php" and alert the result of the request

$.get("test.php", function(data){
  alert("Data: " + data);
});

Parameter Description
URL Required. Specifies the URL you wish to request
data Optional. Specifies data to send to the server along with the request
function(data,status,xhr) Optional. Specifies a function to run if the request succeeds
Additional parameters:
  • data - contains the resulting data from the request
  • status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")
  • xhr - contains the XMLHttpRequest object
dataType Optional. Specifies the data type expected of the server response.
By default jQuery performs an automatic guess.
Possible types:
  • "xml" - An XML document
  • "html" - HTML as plain text
  • "text" - A plain text string
  • "script" - Runs the response as JavaScript, and returns it as plain text
  • "json" - Runs the response as JSON, and returns a JavaScript object
  • "jsonp" - Loads in a JSON block using JSONP. Will add an "?callback=?" to the URL to specify the callback

Example

Send an HTTP GET request to a page and get a result in request:

$("button").click(function(){
  $.get("demo_test.asp", function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
Try it Yourself

jQuery getJSON() Method

The getJSON() method is used to get JSON data using an AJAX HTTP GET request

Syntax:

$(selector).getJSON(url, data, success(data, status, xhr))

Parameter Description
url Required. Specifies the url to send the request to
data Optional. Specifies data to be sent to the server
success(data,status,xhr) Optional. Specifies the function to run if the request succeeds
Additional parameters:
  • data - contains the data returned from the server.
  • status - contains a string containing request status ("success", "notmodified", "error", "timeout", or "parsererror").
  • xhr - contains the XMLHttpRequest object

Example

$("button").click(function(){
  $.getJSON("demo_ajax_json.js", function(result){
    $.each(result, function(i, field){
      $("div").append(field + " ");
    });
  });
});
Try it Yourself

jQuery getScript() Method

The getScript() method is used to get and execute a JavaScript, using an AJAX HTTP GET request

Syntax:

$(selector).getScript(url,success(response,status))

Parameter Description
url Required. Specifies the url to send the request to
success(response,status) Optional. Specifies the function to run if the request succeeds
Additional parameters:
  • response - contains the result data from the request
  • status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")

Example

$("button").click(function(){
  $.getScript("demo_ajax_script.js");
});
Try it Yourself

jQuery param() Method

The param() method creates a serialized representation of an array or an object. The serialized values can be used in the URL query string when making an AJAX request.

Syntax:

$.param(object,trad)

Parameter Description
object Required. Specifies an array or object to serialize
trad Optional. A Boolean value specifying whether or not to use the traditional style of param serialization

Example

$("button").click(function(){
  $("div").text($.param(personObj));
});
Try it Yourself

jQuery post() Method

The $.post() method use to load the data from the server using a HTTP POST request.

Syntax:

$(selector).post(URL,data,function(data,status,xhr),dataType)

Parameter Description
URL Required. Specifies the url to send the request to
data Optional. Specifies data to send to the server along with the request
function(data,status,xhr) Optional. Specifies a function to run if the request succeeds
Additional parameters:
  • data - contains the resulting data from the request
  • status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")
  • xhr - contains the XMLHttpRequest object
dataType Optional. Specifies the data type expected of the server response.
By default jQuery performs an automatic guess.
Possible types:
  • "xml" - An XML document
  • "html" - HTML as plain text
  • "text" - A plain text string
  • "script" - Runs the response as JavaScript, and returns it as plain text
  • "json" - Runs the response as JSON, and returns a JavaScript object
  • "jsonp" - Loads in a JSON block using JSONP. Will add an "?callback=?" to the URL to specify the callback

Example

Change the text of a <div> element using an AJAX POST request:

$("input").keyup(function(){
  var txt = $("input").val();
  $.post("demo_ajax_gethint.asp", {suggest: txt}, function(result){
    $("span").html(result);
  });
});
Try it Yourself

jQuery ajaxComplete() Method

The ajaxComplete() method specifies a function to be run when an AJAX request completes.

Note: As of jQuery version 1.8, this method should only be attached to document.

Syntax:

$(document).ajaxComplete(function(event,xhr,options))

Parameter Description
function(event,xhr,options) Required. Specifies the function to run when the request completes
Additional parameters:
  • event - contains the event object
  • xhr - contains the XMLHttpRequest object
  • options - contains the options used in the AJAX request

Example

$(document).ajaxStart(function(){
  $("#wait").css("display", "block");
});

$(document).ajaxComplete(function(){
  $("#wait").css("display", "none");
});
Try it Yourself

jQuery ajaxError() Method

The ajaxError() method specifies a function to be run when an AJAX request fails.

Note: As of jQuery version 1.8, this method should only be attached to document.

Syntax:

$(document).ajaxError(function(event,xhr,options,exc))

Parameter Description
function(event,xhr,options,exc) Required. Specifies the function to run if the request fails
Additional parameters:
  • event - contains the event object
  • xhr - contains the XMLHttpRequest object
  • options - contains the options used in the AJAX request
  • exc - contains the JavaScript exception, if one occurred

Example

$(document).ajaxError(function(){
  alert("An error occurred!");
});
Try it Yourself

jQuery ajaxSend() Method

The ajaxSend() method specifies a function to run when an AJAX requests is about to be sent.

Syntax:

$(document).ajaxSend(function(event,xhr,options))

Parameter Description
function(event,xhr,options) Required. Specifies the function to run if the request succeeds
Additional parameters:
  • event - contains the event object
  • xhr - contains the XMLHttpRequest object
  • options - contains the options used in the AJAX request

Example

Change the content of a <div> element when an AJAX requests is about to be sent:

$(document).ajaxSend(function(e, xhr, opt){
  $("div").append("<p>Requesting: " + opt.url + "</p>");
});
Try it Yourself

jQuery ajaxStart() Method

The ajaxStart() method define a function to be run when an AJAX request starts

Note: As of jQuery version 1.8, this method should only be attached to document.

Syntax:

$(document).ajaxStart(function())

Parameter Description
function() Required. Specifies the function to run when the AJAX request starts

Example

Show a "loading" indicator image when an AJAX request starts

$(document).ajaxStart(function(){
  $(this).html("<img src='demo_wait.gif'>");
});
Try it Yourself

jQuery ajaxStop() Method

The ajaxStop() method specifies/define a function to run when ALL AJAX requests have completed.

When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending

Syntax:

$(document).ajaxStop(function())

Parameter Description
function() Required. Specifies the function to run when all AJAX requests have completed

jQuery ajaxSuccess() Method

The ajaxSuccess() method specifies a function to be run when an AJAX request is successfully completed.

Syntax:

$(document).ajaxSuccess(function(event,xhr,options))

Parameter Description
function(event,xhr,options) Required. Specifies the function to run if the request succeeds
Additional parameters:
  • event - contains the event object
  • xhr - contains the XMLHttpRequest object
  • options - contains the options used in the AJAX request

jQuery serialize() Method

The serialize() method creates a URL encoded text string by serializing form values.

You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

Syntax:

$(selector).serialize()

Example

$("button").click(function(){
  $("div").text($("form").serialize());
});
Try it Yourself

jQuery serializeArray() Method

The serializeArray() method creates an array of objects (name and value) by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself.

Syntax:

$(selector).serializeArray()

Example

Output the result of form values serialized as arrays

$("button").click(function(){
  var x = $("form").serializeArray();
  $.each(x, function(i, field){
    $("#results").append(field.name + ":" + field.value + " ");
  });
});
Try it Yourself

We will learn about Miscellaneous references in next chapter Click