Shakil Shakil - 1 year ago 63
jQuery Question

Sending JSON to PHP using ajax

I want to send some data in json format to php and do some operation in php. My problem is i can't send json data via ajax to my php file.Please help me how can i do that. I have tried this way..

$(function (){
var bid=$('#bid').val();
var myqty=new Array()
var myprice=new Array()



var postData =
var dataString = JSON.stringify(postData);

type: "POST",
dataType: "json",
url: "add_cart.php",
data: {myData:dataString},
contentType: "application/json; charset=utf-8",
success: function(data){
alert('Items added');
error: function(e){

And in PHP i use:

$obj = json_decode($_POST['myData']);
//some php operation

When in add print_r($_POST) in php file, it shows array(0) {} in firebug.

Answer Source

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];