Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
?>
share|improve this question
    
Can you post what does echo $value; gives? –  DKasipovic Apr 10 at 7:22
    
now echo $value; gives "Array", how can i get the array content? –  user1887339 Apr 10 at 7:57
    
Try var_dump($value). –  deceze Apr 10 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? –  user1887339 Apr 10 at 8:05
    
*cough*cough* Try var_dump($value) to see what you have and what you're trying to work with. *cough*cough* –  deceze Apr 10 at 8:08
show 2 more comments

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.