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

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.