IT:AD:JSON:HowTo:POST JSON back to the Server
Summary
In traditional web services one posts back using application/x-www-form-urlencoded (multipart/form-data if dealing with file uploading).
But as we move to IT:AD:Single Page App (SPA) architectures, and APIs, we are now querying, and posting back, to API endpoints, using JSON.
Process
JQuery does not have a JSON Serializer. * The argument being that it doesn't need one internally, and can handle it as follows:
$.post("test.php", { name: "John", time: "2pm" } );
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});
In all 3 cases (including last) the serialization in these cases is not the same as JSON.Stringify(),
instead the data is serialised into a html query string.
Therefore, as expressed here use JSON2.js to allow use of Builtin JSON object if available, or use code if not:
That way you can do (see here):
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({"foo": "bar"}),
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});