Ajax


$.ajax()

Basic Syntax

  • $.ajax(url [, options])
  • return jqXHR instance
  • Events

    • success (Anything data, string textStatus, jqXHR jqXHR)
    • error (jqXHR jqXHR, string textStatus, string error)
    • complete (jqXHR jqXHR, string status)
    • beforeSend (jqXHR jqXHR, settings)
  • Global Events (use to monitor all Ajax queries)

  • data (JSON.stringify($("form").serializeArray()))

  • contentType: "application/json; charset=utf-8" (MIME type for JSON)

AJAX requests run asynchronously -- that means that the $.ajax method return before the request is finished, and thereforce before the success callback runs.

Standard way to make jQuery Ajax call


$.ajax(url, settings);
settings.success(data, status, xhr);
settings.error(data, status, errorThrown);
settings.always(xhr, status);
settings.complete();

function getEmail(userEmail, onSuccess, onError) {       
     $.ajax("/email?" + userEmail, { 
         success: onSuccess,              
         error: onError       
     });
}

Another way structure the code

// 

$.ajax({
    data: someData,
    dataType: 'json',
    url: '/path/to/script',
    success: function(data, textStatus, jqXHR) {
        // When AJAX call is successfuly
        console.log('AJAX call successful.');
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // When AJAX call has failed
        console.log('AJAX call failed.');
        console.log(textStatus + ': ' + errorThrown);
    },
    complete: function() {
        // When AJAX call is complete, will fire upon success or when error is thrown
        console.log('AJAX call completed');
    };
});

// Sending data and working with forms

var formData = $(form).serialize();
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            $(formMessages).text(response);

            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
        })
        .fail(function(data) {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

$.load

Fetch snippets of HTML from the server and place them within the DOM. This method is extremely handy and well suited to web application that are powered by servers capable of server-side templating. The load() method is tremendously useful when you want to grab a fragment of HTML to stuff into the content of an element (or set of elements).

   $('#boot-chooser-control')
   .load('actions/fetch-boot-style-options.php')
   .change(function(event) {
       $('#product-detail-pane').load(
             'actions/fetch-product-details.php',
               {
               model: $(event.target).val()
               },
               function() {
                   $('[value=""]', event.target).remove();
               }
       );
   });

$.get

Intended to be idempotent; the same GET operation, made again and again, should return exactly the same results

  $('#boot-chooser-control')
     .load('actions/fetch-boot-style-options.php')
     .change(function(event) {
         // using get utility method 
         // url, data, callback
         $.get(
                // 1. url 
                'actions/fetch-product-details.php', 
                // 2. requested data 
                {
                   model: $(event.target).val()
                },
                // 3. callback function with response
                function(response) {
                      $('#product-detail-pane').html(response);
                      $('[value=""]', event.target).remove();
               }
           );
    });
  • $(this).serialize()

    Create a string representation of the value in the form.

$.post

Can be non-idempotent; the data they send to the server can be used to change the model state of the application -- for example, adding or updating records in a database or removing information from the server.

$.post() utility function is identical to $.get() expect for employing the POST HTTP method.

Any parameters passed within the body of the request.

$.getJSON

$.getJSON('../CustomerJson.aspx',
          {id:1},
          function (data) {
             alert('CustomerID: ' + data.ID + ' Name: ' +
             data.FirstName + ' ' + data.LastName);
         }
   );

$.active

Reference

results matching ""

    No results matching ""