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

Parsing the returned JSON using jQuery


Finally, it's time to see how to get the returned JSON from the server and use it. You'll do this by registering an event handler on $.ajax to receive the resulting JavaScript object, which jQuery helpfully deserializes from JSON for you.

How to do it...

To get the result from the AJAX request, we need to add an event handler to the jQuery XMLHttpRequest object's done event, as follows:

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

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

How it works...