Sending JSON to your web server

Some AJAX requests just need to get data at a URL. This is the case when the server updates an object for all clients, or when the URL for an object uniquely identifies the object (common when you design a service using Representational State Transfer (REST)). Other times, you may want to pass JavaScript data to the server, such as when you have a complex query you'd like the server to process. To do this, create your JavaScript object, then stringify it and pass the string containing the JSON to the XMLHttpRequest object's send method.

How to do it...

Omitting the code that creates an XMLHttpRequest object, you send JSON to a server with the following code:

function doAjax() { // … create XMLHTTPObject as before var ...

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.