Tutorialsteacher

Follow Us

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</code></pre>
        <div className="card-footer example-footer"></div></div>
</div>
    <p>
        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.
    </p>

    <p>
        You can also attach fail and done callback methods to post() method as shown below.
    </p>

    <div className="card code-panel">
        <div className="card-header example-title">Example: jQuery post() Method</div>
        <div className="panel-body"><pre className="csharpcode"><code>$.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>