jQuery Ajax Sending JSON data


jQuery makes handling jSON responses painless, but a bit more work is required when a given request wishes you to send data in JSON format:

 $.ajax("/json-consuming-route", {
      data: JSON.stringify({author: {name: "Bullwinkle J. Moose", 
                                     email: "bullwinkle@example.com"} }),
      method: "POST",
      contentType: "application/json"

Observe that we're specifying the correct contentType for the data we're sending; this is a good practice in general and may be required by the API you're posting to - but it also has the side-effect of instructing jQuery not to perform the default conversion of %20 to +, which it would do if contentType was left at the default value of application/x-www-form-urlencoded. If for some reason you must leave contentType set to the default, be sure to set processData to false to prevent this.

The call to JSON.stringify could be avoided here, but using it allows us to provide the data in the form of a JavaScript object (thus avoiding embarrassing JSON syntax errors such as failing to quote property names).