Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
Try sending the array as a parameter? I don't think the javascript scope can access variables outside a function – PRPGFerret Aug 10 at 17:37
That could be, but then why does it see its contents when using alert inside the function? – Lik Bez Pujanki Aug 10 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) – Adrian Tanase Aug 10 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. – Lik Bez Pujanki Aug 10 at 18:15
this a scope problem. arr is undefined (most probably) in the 1st snippet. – itachi Aug 10 at 18:23
show 1 more comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.