1

I am trying to send json in ajax using javascript. I am able to retrieve the values back from php but unable to retrieve a specific json array.

var mname = ["john", "mary", "eva"];
var fname = 678;
clicked_keyword_test = {"lastName": fname, "firstName": mname};
xmlhttp.send('myArray=' +JSON.stringify(clicked_keyword_test));

Getting data in PHP and sending it back to ajax:

 $receive_data = json_decode ($_POST['myArray']); 
 echo json_encode($receive_data);

Now the above works fine but if I want to retrieve only the values of "firstName" like echo json_encode($receive_data["firstName"]); then I get an error like:

 <b>Fatal error</b>:  Cannot use object of type stdClass as array in.....

How can I sucessfully send json data using javascript not jquery.

user2567857
  • 465
  • 6
  • 24

2 Answers2

3

You should set the second parameter of json_decode to true in order to return an associative array.

$receive_data = json_decode ($_POST['myArray'], true);

http://php.net/manual/en/function.json-decode.php

Jonathon
  • 13,610
  • 9
  • 63
  • 84
1

In PHP stdClass is the base class from which all other objects are derived. All objects in deserialised JSON data assume this type as no other definition is communicated. Properties of objects are accessed using the following notation:

$dataObj->varName;

json_decode also has an optional second parameter which coerces objects to associative-arrays which is how you are trying to access the property.

Emissary
  • 9,018
  • 8
  • 50
  • 58
Cas Wolters
  • 371
  • 3
  • 11