1

I'm having a weird problem here and I can't seem to figure out why I can't pass one array to the PHP script using ajax, but I can pass another array without any problems.

Here's my ajax function:

function update(){

    var hr = new XMLHttpRequest();

    var url = "update.php";

    var vars = "array="+arr;
    hr.open("POST", url, true);

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    hr.send(vars);

}

The variable "arr" is a 2d array loaded with coordinates, like so: [[2,3],[4,5],[5,2]...] and it's user-generated, every time user inserts new set of coordinates, I use PUSH to add them to the array.

It is declared just above this function, inside the javascript.

This seems to be working fine, because when I do alert(JSON.stringify(arr)); inside the ajax function, I can see clearly the coordinate pairs pop up in my browser.

However, when I catch the array on the other side (php script) and write it into a notepad file using:

<?php

$fp=fopen("ajax.txt","w");

$data = $_POST['array'];

fwrite($fp,$data);

fclose($fp);


?>

The file ajax.txt is created but remains empty.

However, when I initialize another array (arr1) inside the ajax function, like this:

function update(){

    var arr1=[[2,3],[4,5],[5,7]];
    var hr = new XMLHttpRequest();

    var url = "update.php";

    var vars = "array="+arr1;
    hr.open("POST", url, true);

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    hr.send(vars);

}

The PHP script seems to write the array to the notepad file without any problems! Why does this happen? Clearly the "arr" variable is not empty, because we can see the contents of it using alert.

Any ideas?

6
  • Try sending the array as a parameter? I don't think the javascript scope can access variables outside a function Commented Aug 10, 2013 at 17:37
  • That could be, but then why does it see its contents when using alert inside the function? Commented Aug 10, 2013 at 17:38
  • I think you cannot pass the array, because what it actually does is update.php?my_variable=15&my_other_var=24&my_text=cheers (i think you can envision that you cannot pass an array like that) Commented Aug 10, 2013 at 18:10
  • Well, if you take a look at the last code snippet I posted, you can see that I obviously can pass an array like that, and it gets through without any problems. Commented Aug 10, 2013 at 18:15
  • this a scope problem. arr is undefined (most probably) in the 1st snippet. Commented Aug 10, 2013 at 18:23

0

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.