How to set the raw body in jQuery Ajax?

JavascriptJqueryPost

Javascript Problem Overview


Instead of sending a list of key/value pairs, I need to send a JSON string as the body of the POST request.
I make this POST request using jQuery's $.ajax function.
How do I set it correctly?

When I say JSON string, I mean something like: {action:'x',params:['a','b','c']} .

This is how I would use this JSON string in PHP on the server:

var_dump(json_decode(file_get_contents('php://input')));

Results in:

stdClass Object
	action = x
	params = Array
        (
	0 = a
	1 = b
	2 = c
        )

Javascript Solutions


Solution 1 - Javascript

Try:

$.ajax('url',{
	'data': JSON.stringify(yourJSONObject), //{action:'x',params:['a','b','c']}
	'type': 'POST',
	'processData': false,
	'contentType': 'application/json' //typically 'application/x-www-form-urlencoded', but the service you are calling may expect 'text/json'... check with the service to see what they expect as content-type in the HTTP header.
});

Hope this helps,

Pete

Solution 2 - Javascript

if you dont specify the key i think it will post as the body without the key like

$.ajax({
data:JSON.stringify({action:'x',params:['a','b','c']})
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionItay Moav -MalimovkaView Question on Stackoverflow
Solution 1 - JavascriptpeteView Answer on Stackoverflow
Solution 2 - JavascriptRafayView Answer on Stackoverflow