jQuery post() method:
The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response.
Syntax:
$.post(url,[data],[callback],[type]);
Parameter Description:
- url: request url from which you want to submit & retrieve the data.
- data: json data to be sent to the server with request as a form data.
- callback: function to be executed when request succeeds.
- type: data type of the response content.
Let's see how to submit data and get the response using post() method. Consider the following example.
Example: jQuery post() method
$.post('/jquery/submitData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, jqXHR) {// success callback
$('p').append('status: ' + status + ', data: ' + data);
})
<p></p>
In the above example, first parameter is a url to which we want to send http POST request and submit the data.
Internally, post() method calls ajax() method with method option to POST. Visit
james.padolsey.com/jquery and search for post() method to see the jQuery source code.
The second parameter is a data to submit in JSON format, where key is the name of a parameter and value is the value of parameter.
The third parameter is a success callback function that will be called when request succeeds. The callback function can have three parameters; data, status and jqXHR. The data parameter is a response coming from the server.
The following example shows how to submit and retrieve JSON data using post() method.
Example: submit JSON data using post() method
$.post('/submitJSONData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, xhr) { // success callback function
alert('status: ' + status + ', data: ' + data.responseData);
},
'json'); // response data format
In the above example, please notice that last parameter is a type of response data. We will get JSON data as a server response. So post() method will automatically parse response into JSON object. Rest of the parameters are same as first example.
You can also attach fail and done callback methods to post() method as shown below.
Example: jQuery post() method
$.post('/jquery/submitData',
{ myData: 'This is my data.' },
function(data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data);
}).done(function() { alert('Request done!'); })
.fail(function(jqxhr, settings, ex) { alert('failed, ' + ex); });
<p></p>
Points to Remember :
- $.post() method allows you to send asynchronous http POST request to submit and retrieve the data from the server without reloading whole page.
- Syntax:
$.post(url,[data],[callback],[type])
- Specify type parameter for the type of response data e.g. specify 'JSON' if server return JSON data.
- Internally post() method calls ajax() method only by passing method='POST' as option.