1

is there anyway to import a javaScript array from a PHP return value?

Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.

$.get(makeArray.php, function(data){
    var responseArray = new Array(data);
    alert(responseArray[1]);
    ...

However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.

Thanks!

2 Answers 2

3

You can use JSON.

In PHP

$myarray = array('first','second','third');
return json_encode($myarray);

In JavaScript:

$.get(makeArray.php, function(data){
  console.log(data[1]); //=> "second"
}, 'json');

Edit

If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:

PHP:

echo join('%',$myarray);

JS:

var array = data.split('%');
Sign up to request clarification or add additional context in comments.

5 Comments

+1. You just beat me. Could also use $.getJSON() instead of $.get().
That is a great answer for most looking to solve similar issues as mine above, however servers running PHP 5.1.6, so can't implement it...
Indeed. I think akash4eva already came up with the solution. But thanks, though...
Or in this case knowing that you are sending a comma-delimited list of strings just echo an opening [, then the values, then a closing ]. Instant JSON. (Yes, hand-coding JSON is not usually a good plan, but for a simple array with a version of PHP that doesn't have json_encode() I don't think it's a problem.)
0

Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.

What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.

3 Comments

That's a pretty nifty solution. As I can't use JSON (see below) I think this is the only way to go about the issue. Thanks.
@Matte Select my answer as the chosen one if this thing works out for you. I would owe you for this. Thanks for appreciating!
yeh, yeh, still a few minutes to go before the system lets me.

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.