O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required