I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"}
but using JQuery the server receive name=jonas
. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
Base on lonesomeday's answer, I create a
jpost
that wraps certain parameters.Usage:
Using
Promise
and checking if thebody
object is a valid JSON. If not a Promisereject
will be returned.I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
You're passing an object, not a JSON string. When you pass an object, jQuery uses
$.param
to serialize the object into name-value pairs.If you pass the data as a string, it won't be serialized: