jQuery - Ajax

jquery

http://www.sitepoint.com/use-jquerys-ajax-function/
http://www.sitepoint.com/ajax-jquery/
http://www.sitepoint.com/introduction-jquery-shorthand-ajax-methods/
http://www.sitepoint.com/store/jquery-novice-to-ninja-new-kicks-and-tricks/
http://api.jquery.com/category/ajax/
http://net.tutsplus.com/tutorials/javascript-ajax/uncovering-jquerys-hidden-features/

How can we submit a form via AJAX?

var myForm =  $('#my-form');
jQuery.post('submit.php', myForm.serialize(), function(){
    alert('Data has been sent!');
});

How can we make a AJAX request using the $.ajax utility method?

jQuery.ajax({
    url: '/qmanagement/controller/qmanagementController?ServName=ManageUserSettings&sCheck=N&mode=GET_USER_SETTINGS',
    data: {},
    type: 'POST',
    success: function(data, textStatus, jqXHR ) {
        jQuery('#msgUpdate').html('User reset successfully!');
        setTimeout(function(){closeResetUnblockWindow();}, 800);
    }
});

See the official documentation for a full list of options.

Why does jQuery allow us to attach functions to specific DOM element during Ajax?

In addition to the ability to specify default functions to be executed for all Ajax requests by establishing them as defaults with $.ajaxSetup(), jQuery also allows us to attach functions to specific DOM elements. These functions will be triggered during the various phases of Ajax request processing or when a request ultimately succeeds or fails. For example, to attach a function to an element whose purpose is to display error message:

$('#errorConsole').ajaxError(reportError);

The function reportError will be called in the event that any Ajax request fails. When this, or any other of these global functions is invoked, the first parameter passed to the callback function consist of a JavaScript object instance with the following two properties:

  1. type: A string that contain the name of global function invoked.
  2. target: A reference to the DOM element to which the global function was attached. In the previous example, it is the element with the ID of errorConsole.

The commands that can be used to attach these global functions are ajaxStart, ajaxSend, ajaxSuccess, ajaxError, ajaxComplete, ajaxStop.

What is the purpose of the param methods?

The 'param' helper function (which exists under the jQuery namespace) takes a regular object and returns a query string, e.g:

var data = {
    name: 'Joe',
    age: 44,
    profession: 'Web Developer'
};
jQuery.param(data); // => "name=Joe&age=44&profession=Web+Developer"

The jQuery.param(data) returns a string: name=Joe&age=44&profession=Web+Developer

What is the purpose of the serializeArray method?

Not sure.

What is the return value of the jQuery.ajax method?

The jQuery.ajax method returns the XHR Object. jQuery's Ajax utility functions ('jQuery.ajax', 'jQuery.get', 'jQuery.post') all return an 'XMLHttpRequest' object which you can use to perform subsequent operations on any request. For example:

var curRequest;

jQuery('button.makeRequest').<wbr>click(function(){
    curRequest = jQuery.get('foo.php', function(response){
        alert('Data: ' + response.responseText);
    });
});

jQuery('button.cancelRequest')<wbr>.click(function(){
    if (curRequest) {
        curRequest.abort(); // abort() is a method of XMLHttpRequest
    }
});

Here we're making a request whenever the 'makeRequest' button is clicked — and we're cancelling the active request if the user clicks the 'cancelRequest' button.

How can we make a non-async HTTP request?

var myRequest = jQuery.ajax({
    url: 'foo.txt',
    async: false
});

console.log(myRequest.<wbr>responseText);

How can we use the load method?

load(url, parameters, callback)

The load method initiate an Ajax request to the specified URL with optional parameters. A callback function can be specified that's invoked when the request completes. The response text replaces the content of all matched elements.

  1. url: (String). The URL of the request.
  2. parameters: (Object). An object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
  3. callback: (Function). A callback function invoked after the response data has been loaded into the elements of the matched set. The parameters passed to this function are the response text, the status code, and the XHR instance.

When the parameters object is used to supply the request parameters, the request is made using the POST HTTP method. Otherwise, a GET request is initiated. If we want to make a GET request with parameters, we can include them as part of the query string on the URL, but we must make sure that they are properly URL-encoded.

$('.injectMe').load('/someURL');
$('.injectMe').load('/someURL', parameters);
$('.injectMe').load('/someURL', parameters, callback);

How can we filter out parts of the response before injecting the response into the DOM using the load method?

Most of the time, we will use load() to inject the complete response into whatever elements are contained within the wrapped set, but sometimes we may want to filter elements coming back as the response. If we want to filter response elements, jQuery allows us to specify a selector on the URL that will be used to limit which response elements are injected into the wrapped elements by suffixing the URL with a space and pound sign character (#) followed by the selector. For example, to filter response elements so that only <div> instances are injected:

$('.injectMe').load('/someURL #div')

What is included by the serialize() method?

The serialize() method is smart enough to only collect information from from control elements that are inside the form elements inside the wrapped set, and only from those qualifying elements that are deemed successful. A successful control is one that would be included as part of a form submission according to the rules of the HTML Specification. Controls such as unchecked check boxes and radio buttons, dropdowns with no selections, and any disabled controls are not considered successful and do not participate in the submission. They are ignored by serialize().

What is the difference between serialize() and serializeArray()?

If we'd rather get the form data in a JavaScript array, as opposed to a query string, use the serializeArray() method. In other words, serialize() returns a string, and serializeArray() returns an array.

The array returned by serializeArray() is composed of anonymous object instances, each of which contains a name property and a value property that contains the name and value of each successful form control.

How can we make AJAX call using the get utility function?

$.get(url, parameter, callback);

Initiate a GET request to the server using the specified URL with any passed parameters as the query string.

  1. url: (String). The URL of the server-side resource to contact via the GET method.
  2. parameters: (Object | String). An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded string.
  3. callback: (Function). A function invoked when the request completes. The response body is passed as the first parameter to this callback, and the status as the second.

How can we make an AJAX request using the getJSON utility method?

$.getJSON(url, parameters, callback)

Initiate a GET request to the server using the specified URL with any passed parameters as the query string. The response is interpreted as a JSON string, and the resulting data is passed to the callback function

  1. url: (String). The URL of the server-side resource contacted via the GET method.
  2. parameters: (Object | String). An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.
  3. callback: (Function). A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.

How can we make AJAX request using the $.post() utility method?

$.post(url, parameters, callback);

Initiate a POST request to the server using the specified URL with any parameters passed within the body of the request.

  1. url: (String). The URL of the server-side resource to contact via the POST method.
  2. parameters: (Object | String). An object whose properties serve as the name/value pairs used to construct the body of the requests, or a preformatted and encoded query string.
  3. callback: (Function). A function when the request completes. The response body is passed as the single parameter to this callback, and the status as the second.

What is the purpose of the $.ajaxSetup() utility function?

Setup up the default properties or settings for subsequent ajax calls.

$.ajaxSetup(properties)
  1. properties: (Object). An object instance whose properties define the set of default Ajax properties. These are the same properties used by the $.ajax utility function.
$.ajaxSetup({
  timeout: 5000,
  error: function(xhr) {
    $('#errorDisplay').html('Error: ' + xhr.status + ' ' + xhr.statusText);
  }
});
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License