jQuery provides a quick, robust and easy way to request data from the server without a page reload through AJAX. In this short article we’ll look at loading data from the server using a HTTP Post Request.
jQuery $.post function
There is a shorthand AJAX post function with the following signature:
jQuery $.post Example
$.post({
  url: 'myTargetURL.php',
  data: data,
  success: success function(data, textStatus, jqXHR),
  dataType: dataType
});
jQuery $.ajax Post Function
I prefer to use the default .ajax function for ease of use and maintainability.
jQuery $.ajax Example
$.ajax({
type: 'POST',
url: 'myTargetURL.php',
data: data,
success: success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
jQuery AJAX Post Parameters
Here is the rundown on pass parameter: > type - HTTP Request Type. In this case ‘POST’, but could be ‘GET’ as well.url - A string containing the URL to which the request is sent. Eg: HTTP://www.Yourdomain.com/YourAjaxScript.php
data - A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR) - A callback function that is executed if the request succeeds.
complete() - A callback function that is executed when everything is complete.
dataType - The type of data expected from the server. Default: Intelligent Guess (xml, json, <script, text, html).
jQuery Ajax Error Handling
The jQuery $.ajax function has a very robust error handling system. You can read more about it’s implementation in the jQuery Ajax Error Handling Function post.
jQuery Ajax Post Example
$.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData,
        // callback handler that will be called on success
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("It worked!");
        },
        // callback handler that will be called on completion
        // which means, either on success or error
        complete: function(){
            // enable the inputs
            $inputs.removeAttr("disabled");
        }
    });
comments powered by Disqus