Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Getting the progress of a request using jQuery


jQuery abstracts the various progress reporting mechanisms of the underlying XMLHttpRequest object in a platform-agnostic way, giving you the ability to determine whether your request succeeded or failed. You do this by registering functions that the jQuery AJAX handler will invoke when an error occurs or the results are successfully loaded.

How to do it...

Here's doAjax rewritten to support getting notifications on failure, regardless of whether the event succeeds or fails:

function doAjax() {
  $('#debug').html("loaded... executing.");
 
  var request = { 
    call: "kf6gpe-7"
  };

  $.ajax({
    type: "POST",
    url: "/",
    data: JSON.stringify(request),
    dataType:"json",
  })
  .fail(function() {
    $('#debug').append("<br/>failed");
  })
  .always(function() {
    $('#debug').append("<br/>complete");
  });
}

The new methods here are the fail and always methods.

How it works…

jQuery uses a pattern called chaining, in which...