jQuery Introduction | Using Ajax | Ajax Methods $.ajax() $.get() .load()

Ajax methods

Method Description
$.ajax() Sends an HTTP request by using asynchronous Ajax.
$.get() Sends a GET HTTP request to the specified address.
$.post() Sends a POST HTTP request to the specified address.
$.getScript() Adds a script to the web page.
$.getJSON() Sends a GET HTTP request to the specified address and receives a JSON file as the response.
.load() Reads data from the server and places the loaded HTML code into the selected element.

$.ajax() method

jQuery provides many convenient methods related to Ajax.

Among them, the $.ajax() method is the central, integrated method behind all jQuery Ajax methods.
The $.ajax() method provides a powerful and intuitive way to create HTTP requests.

Syntax

jQuery.ajax( url [, settings] ) >> version 1.5 or later
jQuery.ajax( settings )  >> version 1.0 or later
  • url: The request URL, meaning the server address to which the client sends the HTTP request.
  • settings: An Ajax request set made of key/value pairs (optional).
    • url: The request URL.
    • data: A string or JSON sent to the server with the request.
    • success(data, textStatus, jqXHR): A callback function that runs when the request succeeds.
    • dataType: The type of data returned from the server (default: xml, json, script, text, html).

Method chaining

Method name Description
done When the HTTP request succeeds, the requested data is passed to the done() method.
fail When the HTTP request fails, information about the error and status is passed to the fail() method.
always The always() method runs whether the HTTP request succeeds or fails.

Example

The following example explains representative options that can be used with the $.ajax() method.

$.ajax({
    url: "/rest/1/pages/245", // URL address of the server to which the client sends the HTTP request
    data: { name: "Hong Gil-dong" },  // Data to send to the server with the HTTP request
    method: "GET",   // HTTP request method (GET, POST, and so on)
    dataType: "json" // Type of data returned by the server
})
// When the HTTP request succeeds, the requested data is passed to the done() method.
.done(function(json) {
    $("<h1>").text(json.title).appendTo("body");
    $("<div class=\"content\">").html(json.html).appendTo("body");
})
// When the HTTP request fails, information about the error and status is passed to the fail() method.
.fail(function(xhr, status, errorThrown) {
    $("#text").html("An error occurred.<br>")
    .append("Error name: " + errorThrown + "<br>")
    .append("Status: " + status);
})
// 
.always(function(xhr, status) {
    $("#text").html("The request has completed!");
});

The following example is a simple example that shows how the $.ajax() method works.

var jqxhr = $.ajax("/rest/1/pages/245")
.done(function() {
  alert("Success");
})
.fail(function() {
  alert("Failure");
 })
.always(function() {
  alert("Complete");
});
      
jqxhr.always(function() {
  alert("Second success");
});

Run code

$.ajaxSetup() method

This method is used to configure common default Ajax requests in advance.

Syntax

jQuery.ajaxSetup( options )
  • optional: Settings for default Ajax requests (key/value).

Example

The following example sets the default options in $.ajaxSetup() in advance and then calls Ajax separately.

$.ajaxSetup({  
  url: '/api/users',  
  global: false,   
  type: "POST"     
});  

$.ajax({  
  // url not set here; uses '/api/users'  
  data: {'name': 'Dan'}  
});

$.ajax({  
  // url not set here; uses '/api/users'  
  data: {'name': 'John'}  
}); 

$.get() method

jQuery provides the $.get() method, which implements GET HTTP requests by using Ajax.
With this method, you can send a GET HTTP request to the server.

Syntax

jQuery.get(  url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
  • url: The request URL.
  • data: A string or map sent to the server with the request.
  • success(data,textStatus,jqXHR): A callback function that runs when the request succeeds.
  • dataType: The type of data returned from the server (default: xml,json,script,text,html).

Expressed with $.ajax

$.ajax({
  type: "GET",
  url: url,  
  data: data,  
  success: success,  
  dataType: dataType  
});  

The following example is a simple example that shows how the $.get() method works.

// Sends an HTTP request to the server with the GET method.
$.get("/examples/media/request_ajax.php",
  { species: "cat", name: "Nabi", age: 3, }, // Sends the information required by the server.
    function(data, status) {
      $("#text").html(data + "<br>" + status); // Shows the received data and whether the transfer succeeded.
    }
   );
});

$.post() method

jQuery provides the $.post() method, which implements POST HTTP requests by using Ajax.
With this method, you can send a POST HTTP request to the server.

Syntax

The syntax of the $.post() method is as follows.

$.post(URL address[,data][,callback function]);
  • URL address: The server address to which the client sends the HTTP request.
  • data: The data to send to the server with the HTTP request.
  • callback function: Defines the function to run when the HTTP request succeeds.

Expressed with $.ajax

$.ajax({
  type: "POST",
  url: url,  
  data: data,  
  success: success,  
  dataType: dataType  
});  

Example

The following example is a simple example that shows how the $.post() method works.

// Sends an HTTP request to the server with the POST method.
$.post("/examples/media/request_ajax.php",
  { name: "Hong Gil-dong", grade: "A" },    // Sends the information required by the server.
  function(data, status) {
    $("#text").html(data + "<br>" + status); // Shows the received data and whether the transfer succeeded.
  }
);

$.getJSON() method

This method is used when sending data to the server with HTTP GET and receiving the server response in JSON format.

Syntax

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
  • url: The request URL.
  • data: A string or map sent to the server with the request.
  • success(data,textStatus,jqXHR): A callback function that runs when the request succeeds.

Expressed with $.ajax

$.ajax({  
  url: url,  
  dataType: 'json',  
  data: data,  
  success: callback  
});  

Example

$.getJSON("example?foo=1",   
    {   
        tags: "mount rainier",   
        tagmode: "any",   
        format: "json"   
    },   
    function(data) {   
        $.each(data.items, function(i,item) {   
          $("<img/>").attr("src", item.media.m).appendTo("#images");   
          if ( i == 3 )
		      return false;   
        });   
    }); 

.load() method

The load() method is the only jQuery Ajax method called from a selected element.

The load() method reads data from the server and displays the loaded HTML code in the selected element.
Also, if you send a selector with the URL address, only the elements matching that selector in the loaded HTML code are placed.

Syntax

.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
  • url: The request URL.
  • data: A string or map sent to the server with the request.
  • complete(responseText, textStatus, XMLHttpRequest): A callback function that runs when the request completes.

Example

The following examples show several forms of the .load() method.

// Loads HTML content
$('#result').load('ajax/test.html');  
  
// Loads HTML content and then displays a message
$('#result').load('ajax/test.html', function() {  
  alert('Load was performed.');  
});  
  
// Loads the #container target from the HTML content
$('#result').load('ajax/test.html #container');  
  
// Passes an array parameter and loads HTML content
$("#objectID").load("test.asp", { 'choices[]': ["Jon", "Susan"] } );  

The following example is a simple example that shows how the .load() method works.

$(function() {
    $("#btnRequest").on("click", function() {
        // Reads <li> elements from the HTML code at the URL address and places them in the element whose id is "list".
        $("#list").load("/examples.html li");
    });
});

References