I am posting some data to a PHP page with AJAX, but I can't decode it. json_decode()
returned NULL. So I figured that if I'd echo it I could run it through jsonlint. But nothing showed up. To find out if the data reaches the PHP page I tried to var_dump()
the data. Strange enough it showed:
string(75) "{\"title\":\"fds\",\"body\":\"fds\",\"tags\":\"fds\",\"type\":\"question\"}"
So the data reaches the page. I ran it through jsonlint after removing the backslashes and it said the JSON was valid. How is this possible?
I got a valid JSON string of 75 characters according to var_dump()
and jsonlint, but I can't echo
it or json_decode()
it.
EDIT:
Apparently I did something wrong, I can echo it now (I probably made a typo in the $_POST
array key). It echoes this:
{\"title\":\"tre\",\"body\":\"tre\",\"tags\":\"tre\",\"type\":\"question\"}
Once again, without backslashes JSONLint tells me it is valid JSON.
EDIT 2:
Here's the PHP code:
// code to check if the user is logged in
$post = json_decode($_POST['q']);
echo "var_dump(\$_POST['q']): ";
var_dump($_POST['q']);
echo "<BR /><BR />";
echo "var_dump(\$post): ";
var_dump($post);
Ouput:
var_dump($_POST['q']): string(74) "{\"title\":\"gfd\",\"body\":\"gf\",\"tags\":\"gfd\",\"type\":\"question\"}"
var_dump($post): NULL
JS code:
var simpleObj = {title: "rew", body: "rew", tags: "rew", type: "question"};
$.post('savepost.php', "q=" + JSON.stringify(simpleObj), function(data) {
$('#resultDiv').html("DATA: " + data);
});
Final edit:
I finally solved it myself. I actually discovered the problem even before I asked, but thought it was 'harmless' and didn't think that could cause this problem.