jQuery Ajax

XMLHttpRequest: example

ActiveX for IE5 and IE6: code

XMLHttpRequest Object: Methods & Properties

Call Ajax:

  • $.ajax(url[, setting])
$('.confirmation').on('click', 'button', function() {
  $.ajax('url', { 
    success: function(response) { 
      $('.ticket').html(response).slideDown();
    },
    data: {"confNum": 1234 / $(".ticket").data("confNum") },
    error: function(request, errorType, errorMessage) {
      alert("Error:" + errorType + "with message:" + errorMessage);
    }, 
    timeout: 3000,
    beforeSend: function() { ... },
    complete: function() { ... }
  });
});
  • $.get(url, success)
$('.confirmation').on('click', 'button', function() {
  $.get('url', function(response){
    $('.ticket').html(response).slideDown();
  });
});

Javascript Objects: Event Handler Refactor – limited to 1 confirmation per page

var confirmation = {
  init: function() {
    $('.confirmation').on('click', 'button', this.loadConfirmation);
    $('.confirmation').on('click', '.view-boarding-pass', this.showBoardingPass);
  },
  loadConfirmation: function() {
    $.ajax('url', { ... });
   },
   showBoardingPass: function(event) {
     ...;
   }
};

$(document).ready(function() {
  confirmation.init(); 
});

Javascript Functions – can have multiple confirmation per page

function Confirmation(el) {
  this.el = el;
  this.ticket = this.el.find('.ticket');
  var confirmation = this;
  this.loadConfirmation=function(){
    $.ajax('url', {
      timeout: 3000,
      context: confirmation,
      success: function(response) {
        this.ticket.html(response).slideDown();
      }
    });
  }
  this.showBoardingPass=function(event){
    event.preventDefault();
    $(this).hide();
    confirmation.el.find('.boarding-pass').show();
  }
  this.el.on('click', 'button', this.loadConfirmation);
  this.el.on('click', '.view-boarding-pass', this.showBoardingPass);
}

$(document).ready(function() {
  var paris = new Confirmation($('paris'));
  paris.details();
  var london = new Confirmation($('london'));
  london.details();
});

Ajax with Forms: Form Submit

$('form').on('submit', function(event) {
  event.preventDefault();
  var form = $(this);
  $.ajax('url', {
    type: 'POST', 
    data: form.serialize(),
    success: function(result) {
      form.remove();
      $('#vacation').hide().html(result).fadeIn();
    }
  });
});

Ajax with Forms: JSON

$('form').on('submit', function(event) {
  event.preventDefault();
  var form = $(this);
  $.ajax($('form').attr('action'), {
    type: 'POST', 
    data: form.serialize(),
    dataType: 'json',
    success: function(result) {
      form.remove();
      var msg=$("<p></p>");
      msg.append("Destination: " + result.location + ". ");
      msg.append("Price: " + result.totalPrice + ". ");
      msg.append("Nights: " + result.nights + ". ");
      msg.append("Confirmation: " + result.confirmation + ". ");
      $('#vacation').hide().html(msg).fadeIn();
    },
    contentType: 'application/json'
  });
});

Utility Functions – iterate through the array

  • $.each – $.each(collection, function(<index>, <object>) {})
$('.update-status').on('click', function(){
  $.ajax('/status', {
    contentType: 'application/json',
    dataType: 'json',
    success: function(result) {
      $.each(result, function(index, city) {
        var favorite = $('.favorite-' + index);
        favorite.find('p').html(city.name);
        favorite.find('img').attr('src', city.image);
      });
    }
  });
});
  • $.map – $.getJSON(url, success); / $.map(collection, function(<item>, <index>){});
$('.update-status').on('click', function(){
  $.getJSON('/status', function(result) {
    var statusElements = $.map(result, function(status, i) {
      var listItem = $('<li></li>');
      $('<h3>'+status.name+'</h3>').appendTo(listItem);
      $('<p>'+status.status+'</p>').appendTo(listItem);
      return listItem;
    });
  $('.status-list').detach().html(statusElements).appendTo('.status');
  });
});

Ajax Book: Head Rush Ajax by Brett McLaughlin

 

Advertisements

About bernadetteengleman

Hello, I am Bernadette from New York City. I moved here from Chicago in 2013. I am originally from the Philippines. I started studying web programming in 2015. I love it because I like making fun websites and web apps. The projects that I built so far are posted below. I like to cook and I love to travel. I also like to volunteer and I am a team leader with the non-profit organization, NYCares.
This entry was posted in jQuery and tagged , , , , , . Bookmark the permalink.