简体   繁体   中英

Pass PHP Array to Javascript

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM