Tuesday, 27 January 2015

jQuery Ajax Cheat Sheet

jQuery.ajax( url [, settings ] ) performs an Asynchronous HTTP (Ajax) requests using jQuery.

Basic settings

Url

$.ajax({url: '/Products/Details/1234' })

Querystring

$.ajax({url: '/Products/Details?id=1234&showorders=false' })

type: HTTP Method

$.ajax({url: '/Products/Details/1234', type: 'POST' })

data: Data to be sent to the server.It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234} })

$.ajax({url: '/Products/Details', type: 'POST', data: $('form1').serialize() })

var contact = {firstName:"Bob", lastName:"Bob", mobile:"9907833", email: "bob@example.com"};
$.ajax({url: '/Contact/Create', type: 'POST', data: JSON.stringify(contact) })

contentType: Type of data send to the server

default value is 'application/x-www-form-urlencoded; charset=UTF-8'
$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, contentType: 'application/json; charset=UTF-8' })

dataType: type of data expecting from server. If none is specified, jQuery will try to infer it based on the MIME type of the response - xml, json, script, or html

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, dataType: 'html' })

headers: Helps to set http header(s)

$.ajax({url: '/Products/Details', headers: { Accept: "application/json; charset=utf-8", "Content-Type": "application/x-www-form-urlencoded" }, data: $('form1').serialize() })

Handling succeeded request/response

$.ajax({url: '/Products/Details?id=1234',  
               success: function (result, textStatus, jqXHR) {
                    alert("success");
                }
})

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second complete" );
});

Handling failed request/response.

$.ajax({url: '/Products/Details?id=1234',  
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);alert(jqXHR.status);alert(errorThrown);
                }  })

Handling response based of HTTP status code

$.ajax({url: '/Products/Details?id=1234',  
               
statusCode: {
                    201: function (s) {
                        $('#result').html(s);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
})

Ajax Shorthand Methods

jQuery.get() Load data from the server using a HTTP GET request.

$.get( "test.php", function( data ) { $( "body" ).append(data) });

jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.

(function() {
$.getJSON( "example.json", function() {
  console.log( "success" );
})
.done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "" ).attr( "src", item.media.m ).appendTo( "#images" );
      });
    });
})();

jQuery.getScript() Load a JavaScript file from the server using a GET HTTP request, then execute it. jQuery.getScript() sets cache to false by default.

$.getScript("/jscript/test.js")

jQuery.post() Load data from the server using a HTTP POST request. Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

$.post( "/product/list", function( data ) {
  $( ".result" ).html( data );
});

jQuery.load() Load data from the server and place the returned HTML into the matched element.

$( "#result" ).load( "/product/list" );

No comments:

Post a Comment