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

Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.

PHP:

function toggleLayers(){
    for($i=0;$i<$group_layer_row;$i++){
        $toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
        return $toggleArray;
    }
}

JS:

var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
    for(var i=0;i < myArray.length; i++){
        if($myArray.getVisibility()==true){
            $myArray.getVisibility(false);
        }
    else{
        $myArray.getVisibility(true);
    }
}

SQL (for reference):

$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);   
$group_layer_row = mssql_num_rows($rs_group_layer);

I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.

Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"

Thanks for your help.

Edit:

Sorry, my question was very vague. Here's what I'm trying to do:

1.PHP Function gets all records from table into array(in this case they are map layers)

2.Javascript receives PHP array and loops through adding if clause to toggle layers.

Hope this makes it clearer.

share|improve this question
Does it work? What doesn't work? – Dogbert Dec 5 '11 at 9:27
It does not work.. it keeps giving me a [JSON.parse("null")] statement and Object doesn't support property or method 'getVisibility' – Yus Dec 5 '11 at 9:29

3 Answers

up vote 0 down vote accepted

It's simpler than you think.

Change this line:

var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];

To just:

var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;

json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.

NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.

share|improve this answer
Are you sure this works? I don't think you can insert php tags into a JS script like that... – Logan Serman Dec 5 '11 at 9:30
I still get a null value... – Yus Dec 5 '11 at 9:33
Then the problem with your code is not in the json layer, but in the php layer. Your php array is being prepared incorrectly. I added an explanation of your toggleLayers() problem. – Francis Avila Dec 5 '11 at 9:34
Yes, this is a code I received recently and was asked to work on, half of it I am still trying to understand why the original programmer made it this way... – Yus Dec 5 '11 at 9:39
1  
All this code is so full of errors that we can't fix it without rewriting every line. But the answer to your question "how pass a php array into javascript" is answered. – Francis Avila Dec 5 '11 at 9:51
show 2 more comments

A trick I've learned is to json_encode() your array, and echo it out as CDATA before you javascript file.

First lets set up assume an array called $data is what we want to pass. What you need to do first is properly encode html entities, then json_encode the results.

foreach ( (array) $data as $key => $value ) {
       if(!is_scalar($value)
           continue;

       $data[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8');
}
$data = json_encode($data);

Now we just need to assign $data to a javascript variable, I'll call it $js_data in javascript for clarity. We also will need to wrap that all as CDATA

echo "<script type='text/javascript'>\n";
echo "/* <![CDATA[ */\n";
echo "var $js_data = " . $data;
echo "/* ]]> */\n";
echo "</script>\n";

As some other commenters mentioned, you could also accomplish this through an ajax request, to which you would also respond with the json_encoded object, while avoiding the need for CDATA.

Additionally, you could just make php generate your whole javascript file, and depending on your circumstances that might be easiest - although if you do make sure you append a random number to the end of the filename or as a query string, to avoid browsers caching the file - or, set the expiration of the file to be far into the future, if you have access to such things.

As with all javascript, you should know that data passed this way is made publicly available, and is not suited for sensitive information.

P.S. Dirty little secret, I learned this trick from the way WordPress handles javascript I18n. See this and this for reference.

share|improve this answer

A thing that would be very useful to understand:

You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.

Thus, 3 simple step to solve any problem with PHP -> client transfers:

  1. Create a pure client-side code you wish. Make it work. Save it somewhere.
  2. Create a PHP code to produce that client-side code.
  3. Compare the codes. If doesn't match - correct the PHP code. Repeat until done.
share|improve this answer

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.