Reputation: 2410
I have a click event where I compose a json data, then I want to POST it to a PHP file for processing. But something goes wrong. My PHP file is simplified for now looking like this:
<?php
header('Content-Type: application/json');
var_dump($_POST);
?>
And the code for POST-ing looks like this:
// myarray is: var myarray = new Array();
// and it gets populated above this code
var strObj = JSON.stringify(myarray);
alert(strObj); // so far I get the alert containing valid JSON text
$.ajax ({
type:"POST",
url:"proces.php",
contentType: "application/json",
dataType: "json",
async: false,
data: strObj,
success: function(){ alert("success")},
error: function(){ alert("error")}
});
So when I click the button, I receive the alert containing the JSON string (looks fine), then I get the alert saying "error", and when I check the console for the response of proces.php all I see is:
array(0) {
}
What am I doing wrong? What can I do to make it right?
Upvotes: 1
Views: 5577
Reputation: 2410
I got an answer on my own. Seems to do the trick:
$.post("proces.php", {json: JSON.stringify(myarray)}, function(data){alert(data);});
I mean, I do not get the alert(data); (probably because I do not return a JSON back from php file) but in the PHP I can see the json data now.
Upvotes: 1
Reputation: 94
This did the trick for me:
$.ajax ({
type:"POST",
url:"proces.php",
dataType: "json",
async: false,
data: {tmp: strObj},
success: function(){ alert("success")},
error: function(){ alert("error")}
});
Upvotes: 1