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

Sending JSON to your web server using jQuery


Sending JSON to your server using jQuery is easy. Just get the data in the JSON format and specify it using the ajax method argument's data field.

How to do it...

Let's look at doAjax again, this time modified to send our request JSON:

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

  $.ajax({
    type: "POST",
    url: "/",
    data: JSON.stringify(request),
    dataType:"json"
  });
}

</script>
</body>
</html>

How it works…

The magic line in the previous listing is highlighted; it's the following line in the arguments passed to the ajax method:

    data: JSON.stringify(request),

Of course, we use JSON.stringify to encode the JavaScript object as JSON before assigning it to the data field.