jQuery.post() JQ Home  <<  Ajax  <<  jQuery.post()

Asynchronous HTTP (Ajax) load request.

Description

The jQuery.post() Ajax method, allows us to load data from the server, using a HTTP POST request.

Shorthand version $.post()

  • Browsers operate the 'same origin policy', which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery 'Ajax' requests are subject to this security restriction, the exceptions being requests made with a datatype of 'script' or 'jsonp'.
  • The jQuery.post() method returns a jqXHR object which is a superset of the browser's native XMLHttpRequest object. The jqXHR object implements the Promise interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on the Deferred object for details of this. For standardization with the Deferred object, the jqXHR object also provides done(), fail() and always() methods. These methods take a function argument that is called when the jQuery.post() request terminates and the function receives the same arguments as the same-named success(), error() and complete() setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.
    • It should be noted that success(), error() and complete() callbacks are deprecated from use on request completion from jQuery 1.8 and removed in jQuery 3.0. This is for completion processing only and the Ajax settings will still have these values. Best practice is to use done(), fail() and always() methods on request completion to future proof code.
  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:
    jqXHR Object Description
    Methods
    abort()Cancels the currently executing request.
    getAllResponseHeaders()Returns a string containing the names and value of all response headers.
    getResponseHeader(name)Returns the value of the specified response headers.
    .overrideMimeType()Used in the beforeSend() callback function, to modify the response content-type header.
    setRequestHeader(name, value)Set a request header using the specified name and value.
    Properties
    readyStateAn integer indicating the current state of the request.
    responseTextUnderlying request responded with text.
    responseXMLUnderlying request responded with xml.
    statusResponse status code returned from the server.
    statusTextStatus text message returned by the response.


Syntax

Signature Description
jQuery.post( url [, data] [, function( data, textStatus, jqXHR)] [, dataType] )Load data from the server, using a HTTP POST request.
jQuery.post( settings )Load data from the server using a HTTP POST request, passing some request settings.

Parameters

Parameter Description Type
url A string containing the URL to send the request to.String
data An object or string sent to the server with the request.
  • Data sent to the server is appended to the URL as a query string. If the data parameter is an object map, it is converted to a string and url encoded before being appended to the URL.
String or
PlainObject
function(data, textStatus, jqXHR) A callback function executed when the request succeeds.Function
dataType The type of data expected from the server.
  • Default: Inferred based on the MIME type of the response (html, json, script, or xml).
String
settings Default settings can be set globally by using the jQuery.ajaxSetup() method but the settings as described in jQuery.ajax( settings ) can be useful for individual Ajax requests. Various dependant upon settings parameter.

Return

A jqXHR object.

jQuery.post( url [, data] [, function( data, textStatus, jqXHR)] [, dataType] ) ExamplesAjax  <<  Top

Load data from the server, using a HTTP POST request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:



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


In the example below when we press the left button the first time we use the jQuery.post() method in its simplest form just using a url and output some messages dependant upon request success.

When we press the right button the first time we use the jQuery.post() method with a url and a success handler and output some messages dependant upon request success.



$(function(){
  $('#btn8').one('click', function(){
    $.post( "../../../js/post5.js" )
      .done(function() { $('#div5').append('Post request succeeded! <br>'); })
      .fail(function() { $('#div5').append('Post request failed! <br>'); })
      .always(function() { $('#div5').append('Post request ended! <br><br>'); 
    });
  });
  $('#btn9').one('click', function(){
    $.post( "../../../js/post5.js", function(data, textStatus, jqXHR) {
      $('#div5').append('The post request was a success! <br>');
    })
      .done(function() { $('#div5').append('Post request succeeded! <br>'); })
      .fail(function() { $('#div5').append('Post request failed! <br>'); })
      .always(function() { $('#div5').append('Post request ended! <br><br>'); 
    });
  });
      .always(function() { $('#div5').append('Request ended! <br><br>'); 
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/post1.js")
 * is shown below.
 */
 
$(function(){
  var someText = 'Passing some text. ';
  $('#div5').append('Message from post5.js: ' + someText + '<br>');
});


div5. Some initial text.

Press the button below to action the above code:

               

jQuery.post( settings ) ExamplesAjax  <<  Top

Load data from the server using a HTTP POST request, passing some request settings.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  type: 'POST',
  url: url,
  dataType: dataType,
  error: callback
  success: callback
});

In the example below when we press the left button the first time we use the jQuery.post() using a url, dataType and error and success parameters and output a fail messages as the url doesn't exist.

In the example below when we press the right button the first time we use the jQuery.post() using a url, dataType and error and success parameters and output a success message and the contents of the retrieved url.


$(function(){
  $('#btn12').one('click', function(){
    $.post({
      url: "../../../js/post66.js",
      dataType: "script",
      error: function() { 
        $('#div6').append('The request failed! <br><br>');
      },
      success: function() { 
        $('#div6').append('The request was a sucesss! <br><br>');
      }
    });
  });

  $('#btn13').one('click', function(){
    $.post({
      url: "../../../js/post6.js",
      dataType: "script",
      error: function() { 
        $('#div6').append('The request failed! <br><br>');
      },
      success: function() { 
        $('#div6').append('The request was a sucesss! <br><br>');
      }
    });
  });


/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/post2.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div6').append('Message from post2.js: ' + someText + '<br>');
});

div6. Some initial text.

Press the button below to action the above code:

               

Related Tutorials

jQuery Advanced Tutorials - Lesson 9 - Ajax Shorthand Methods