Skip to content Skip to sidebar Skip to footer

Populate Dropdown Onload By Passing Php Array To Javascript Function

im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it aga

Solution 1:

I think this part looks suspicious

<bodyid="body"onclick="cmbRuleField(\'' + <?phpecho json_encode($varArray);?> + '\');"    >

maybe

<bodyid="body"onclick="cmbRuleField(<?phpecho json_encode($varArray);?>)">

is more like it.

One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:

<body id="body"  onclick="cmbRuleField('['a', 'b']')">

you know there is a problem. You want a native Javascript array to be passed like this

<body id="body"  onclick="cmbRuleField(['a', 'b'])">

EDIT

After talking on chat it became clear the top portion of OP's code needed a tweak as well.

header("location: Rules.php?varFields=".http_build_query($varFields));

Solution 2:

The problem has to do with quotes not being terminated here:

...
<bodyid="body"onclick="cmbRuleField(\'' + <?phpecho json_encode($varArray);?> + '\');"    >
...

The JSON created using json_encode will have a lot of double quotes. Try this:

<script>var array = <?phpecho json_encode($varArray);?>;
</script><bodyid="body"onclick="cmbRuleField(array);">

Solution 3:

There is a much easier way. Encode the $varArray as direct HTML options before sending to the browser. For instance:

<selectid="ruleField"><?phpfor ($i = 0; $i < count($varArray); $i++) { ?><optionvalue="<?php= $varArray[$i].val ?>"><?php= $varArray[$i].name ?></option><?php } ?></select>

Solution 4:

Might be because you are calling JSON.stringify on something that is already a string?

Also what is myCars?

..
for (vari in myCars)
..

Possibly rename it to varArray.

or rename varDisplay to varArray.

and lastly try calling JSON.parse instead:

functioncmbRuleField(varArray)//ruleField 
{   
    var varDisplay = JSON.parse(varArray);

        var sel = document.getElementById("ruleField") // find the drop downfor (var i in myCars) 
        { // loop through all elementsvar opt = document.createElement("option"); // Create the new element
            opt.value = varDisplay [i]; // set the value
            opt.text = varDisplay [i]; // set the text
            sel.appendChild(opt); // add it to the select
        }

}

If that didn't work post the html output here so peeps can create a fiddle :)

Post a Comment for "Populate Dropdown Onload By Passing Php Array To Javascript Function"