0

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?

after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"};  outputs nothing either

how can i actually get the array contents?

javascript:

var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};

myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;

 myString = JSON.stringify(myObject); //this line removed

var jsonString = JSON.stringify(myObject);

$.ajax({
    type: "POST",
    url: "n3.php",
    data: {data : jsonString}, 
    cache: false,

    success: function(aaa){ 
        alert("OK");

         $("#pageContent").html(aaa);       
    }
});

php:

<?php
$value = json_decode($_POST['data']);
echo $value;     //this echos the whole json object 
echo $value->{"key"};  //this outputs nothing
?>
7
  • Can you post what does echo $value; gives? Commented Apr 10, 2014 at 7:22
  • now echo $value; gives "Array", how can i get the array content? Commented Apr 10, 2014 at 7:57
  • 1
    Try var_dump($value). Commented Apr 10, 2014 at 8:02
  • i dont want to just output the array, i want to store it into php variables so that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; anyway i can do that? Commented Apr 10, 2014 at 8:05
  • *cough*cough* Try var_dump($value) to see what you have and what you're trying to work with. *cough*cough* Commented Apr 10, 2014 at 8:08

1 Answer 1

2

You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.

Either json_decode it again, or don't double encode it in Javascript.

Sign up to request clarification or add additional context in comments.

Comments

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.