JQuery post data using AJAX using $.post() function and $.ajax() function – with simple examples

JQuery is one of the most extensively used javascript framework on web today. It provides huge set of APIs, to help us to build functionality and with minimum code.
In this post we will see its two most frequently used functions which is used to post data on server side scripts using AJAX. Before JQuery it was a tiresome process to write long code for doing AJAX request or call. But by using JQuery’s very handy $.post() function or $.ajax() function, it becomes a code of a some 4-5 lines. First we will see usage of $.post() function.

$.post() function in Jquery:


URL is required and is the url to send the request to.
data is optional. Its basically the data to send to the server along with the request
function(data,status,xhr) an Optional function. Specifies a callback function to run if the request succeeds.
dataType which is Optional again and it Specifies the data type expected of the server response.
Jquery supports “xml” , “html” ,”text” ,”script” ,”json” , “jsonp” as type options


In above code, .fail() function will be called if the code in callback function got some error. Basically to handle error we will use .fail() function.
Putting together, the code will look like following:

$.ajax() function in Jquery:

Another powerful function to post data on PHP using JQuery is $.ajax() function:
Here is a general format for $.ajax() function:

General Format:

Apart from above parameters we have more options, Refer http://api.jquery.com/jquery.ajax/ for more options. Also, we can use these parameters in any sequence.

Simple Example:

In above example, we will call $.ajax() function on submit event of form having id “searchForm”. Then in .fail() function we will handle the error if occured. In above we simple alter the JSON string we are getting in alert(“error” + JSON.stringify(e));, in real scenarios we will show those graceful manner.

Now, a simple example with $.ajax() function:

Simple but powerful functions. You can also play around some more examples here http://api.jquery.com/jquery.ajax/

Leave a Reply

Your email address will not be published. Required fields are marked *