1

I have a two dimensional array of objects like so:

function test(n){
  this.id = n;
}

var testArray= new Array(2);
for(i = 0; i < testArray.length; i++){
  testArray[i] = new Array(2);
  for(j = 0; j < testArray[i].length; j++){
    testArray[i][j] = new test((2*i)+j);
  }
}

I then stringify it to post using AJAX like so:

var data = {testA: {testB: testArray[0], testC: testArray[1]}}
var text = JSON.stringify(data);

Once I perform the jquery AJAX call:

$.post("test.php",text,function(data){
  alert(data);
});

I cannot work out how to decode and use this object on the PHP side, so far i've tried something like this:

<?php 

$data = json_decode($_POST);
if($data == null){
    echo "fail";
} else {
    echo $data; 
} 

?>

But I get an error that says it expects a string and I'm passing it an array. I've also tried something like

$data = json_decode($_POST['testA']);

and then error doesn't appear but instead it always outputs "fail".

Does anyone know what I need to do on the PHP side so I access the data?

1 Answer 1

2

Why would you run stringify on it? If you just send it like this:

$.post("test.php", data, function(data) {

You should be able to retrieve it like this:

$data = $_POST['testA'];
Sign up to request clarification or add additional context in comments.

5 Comments

I just tried posting the data directly and when i call $data = json_decode($_POST['testA']); I get an error still where it says its expecting a string
There is no json_decode in my answer, because this way, $_POST['testA'] is already an array.
Ah my mistake, ok it works now. Thank you very much :) I understand that I don't need to stringify the data as i'm already putting it in JSON format manually myself. So I was stringifying a JSON object before?
No, you're not using JSON at all now, because it's not necessary.
Oh ok, I understand now. I got confused about what I needed to do to transfer the data across and thought JSON was required. I guess that's where I got confused.

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.