0

I have started messing around with Json, with ajax recently.

I have this javascript code:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};
$.ajax({
    url: "json.php",
    type: "POST",
    contentType: "application/json",
    data: {json: JSON.stringify(json)},
    success: function(res) {
        $("#box").html(res);
    }
});

A few minutes ago, this code worked absolutely fine, when I did echo $json['test']['number']; it returned 1.

But now this won't work at all, it says that 'json' index is UNDEFINED , therefore I tried using contentType: "application/x-www-form-urlencoded", which does work, but I can't get the array items at all.

If I won't pass a true parameter in the json_decode() function, I will receive the following error:

Cannot use object of type stdClass as array

If I will do it I will not get the data, but the response will say "Array".

And that's what I am echoing:

$json = $_POST['json'];
$json = json_decode($json, true);
echo $json['test'][0];

And that is my var_dump of $json:

array(1) {
  ["test"]=>
  array(1) {
    [0]=>
    array(3) {
      ["number"]=>
      int(1)
      ["char"]=>
      string(3) "hey"
      ["bool"]=>
      bool(true)
    }
  }
}

Why is it doing that? why can't I get the values out of it without it returning an Array?

1
  • "var json =" That's not JSON, that's a JavaScript object initializer. JSON is a textual, non-code, data notation. Commented Oct 12, 2013 at 21:40

1 Answer 1

4

Given this:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};

Your PHP code

$json['test']['number'];

would have only worked in the first place if test was not an array. The above, in JavaScript, would look like:

json.test.number;

But test is an Array; it has no number property. In JavaScript, this would be the correct way to find the number:

json.test[0].number;

You need to do the same in PHP:

$json['test'][0]['number'];
Sign up to request clarification or add additional context in comments.

1 Comment

I get it now, making sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.