Monday, 11 August 2014

$.ajax, $.get, $.post, $.getScript, $.getJson differences in jquery

GET vs POST
·         A GET request is used to get data from the server.
·         A POST request is used for modifying data on the server.
When to use GET
If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.
Characteristics of GET:
·         Use GET for safe actions and POST for unsafe actions.
·         GET requests can be cached
·         GET requests can remain in the browser history
·         GET requests can be bookmarked
·         GET requests can be distributed & shared
·         GET requests can be hacked
When to use POST
If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
·         Use POST when dealing with long requests – if you’re sending large amounts of data, or sensitive data over HTTPS, you will want to use POST. Some browser such as Internet Explorer place a limit on the URL string so this may break the action of some forms if you use GET.
You may consider using POST for the following actions:
·         Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
·         Providing a block of data, such as the result of submitting a form, to a data-handling process
·         Extending a database through an append operation
·         Annotation of existing resources
GET vs POST in AJAX calls
Unless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data). This means that GET requests are more responsive – something you need in AJAX environments! Because “Ajax” requests are subject to the same origin policy there is limited security risks when using GET instead of POST. Use GET to “GET” information from the server such as loading a JavaScript file (AJAX shorthand function $.getScript() can be used to do this) or loading a JSON file (AJAX shorthand function $.getJSON() can be used to do this).
jQuery AJAX Functions that use GET as default: $.get(), $.getScript()$.getJSON().load()
jQuery AJAX Functions that use POST as default: $.post()
Example GET AJAX Call – Calling a PHP script to get the number of twitter followers.
1
2
3
4
5
6
7
8
9
10
11
12
13
$.ajax({
  url: ‘/Controllername/ActionName’,
  type: 'GET',
  data: {Id:$(‘#Id’).val()},
  success: function(data) {
    //called when successful
    $('#ajax-results').html(data);
  },
  error: function(e) {
    //called when there is an error
    //console.log(e.message);
  }
});
Example POST AJAX Call – Submitting a login form.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var $form = $("#myForm");
    var url = $form.attr("action") + "?" + $form.serialize();
    $("#" + id).html(url);

$.ajax({
    type: "POST",
    url: action,
    data: $form,
    success: function(response)
    {
        if(response == 'success')
            $("#myForm").slideUp('slow', function() {
                $("#msg").html("<p class='success'>You have logged in successfully!</p>");
            });
        else
            $("#msg").html("<p class='error'>Invalid username and/or password.</p>");
    }
});
Further Readings
Form Submission Example
This example doesn’t really apply to AJAX as these requests happen behind the scenes but may help you understand further what is happening between the different request types.
When using GET a HTTP request is generated and passes the data to the web server as a set of encoded parameters appended to the URL in a query string.
For instance, it would be a bad idea to use GET for a login form submission as the login details would show in the address bar.
1
2
GET /login.php?username=user&amp;password=12345 HTTP/1.1
Host: domain.com
But if we used POST the parameters would be passed within the body of the HTTP request, not in the URL. This would happen behind the scenes between the browser and the web server.
1
2
3
POST /login.php HTTP/1.1
Host: domain.com
username=user&amp;password=12345

GET Caching
GET is intended to be used when you are reading information to display on the page. Browsers will cache the result from a GET request and if the same GET request is made again then they will display the cached result rather than rerunning the entire request.

$.ajax() Performs an asynchronous HTTP (Ajax) request basically this is a method of jquery which internally uses xmlhttprequest object of JavaScript as asynchronous communicator which supports cross browser also.

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.
As their names imply, get() uses the HTTP GET protocol and post() uses the POST protocol.

$.get() function is a shorthand Ajax function, which is equivalent to below expression, Uses some limited criteria like Request type is GET. In $.get() function there is no any error callback only you can track succeed callbackand there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want to customize use $.ajax(). 

get: 
function(url, data, callback, type) {
 if ($.isFunction(data)) {
     callback = data;
     data = null;
 }

 return $.ajax({
       type: "GET",
       url: url,
       data: data,
       success: callback,
       dataType: type
     });
}
$.post() function is a shorthand Ajax function, which is equivalent to below expression, Uses some limited criteria like Request type is POST. In $.post() function there is also no any error callback only you can track succeedcallback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax(). 

post: function(url, data, callback, type) {
    if ($.isFunction(data)) {
        callback = data;
        data = {};
    }

    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}
 
$.getScript() function is a shorthand Ajax function (internally use $.get() with data type JSON), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is script.

$.getJSON() function is a shorthand
 Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.



getScript: function(url, callback) {
     return $.get(url, null, callback, "script");
}
getJSON: function(url, data, callback) {
      return $.get(url, data, callback, "json");
}

And in both of
 the function ($.getScript(), $.getJSON()) there is also no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

No comments :