Reputation: 4345
I have a php that echos html. Inside one of these echos I have a button that calls a javascript function. Inside of this call I pass a php variable. However when I see what the value of one of the elements is inside of the javascript I get undefined.
Any ideas?
Javascript
function addrow(innerid, teams){
alert(teams[1]);}
Here is how I pass it, this is all inside of an echo
<input type = "button" id = '.$buttonid.' value = "Agregar" onclick = "addrow(\'' . $leaguesarray[$numofleagues] . '\','.$teamsarray.')
So I call addrow(with a league value, and I also pass the array teamsarray from php
I've decided to try something else but I'm not getting it to work correctly.
Any suggestions?
echo '<script language="javascript">';
for ($size = 0; $size < sizeof($teamsarray);$size++){
echo "var teamsarray[".$size."] = ".$teamsarray[$size].";\n";
}
echo 'function addrow(innerid, size){
for (var i = 0;i< size; i++ ){
html = html + "<option value = " + teamsarray[i] + ">"+teamsarray[i]+"</option>";
}
html = html +"</select>";
}</script>';
basically what I'm trying to do is echo the javascript through php. I'm trying to make a dropdown with values that I get from php. Which will be added dynamically with the addrow function.
Upvotes: 1
Views: 807
Reputation: 48865
In javascript, arrays look like: [2,4,6]. The php implode command can help here.
$buttonid = 42;
$leaguesarray[$numofleagues] = 66;
$teamsarray = array(2,4,6);
$teams = implode(',',$teamsarray);
$input = <<<EOT
<input type="button" id="$buttonid" value="Agregar" onclick="addrow($leaguesarray[$numofleagues],[$teams])" />
EOT;
echo $input . "\n";
Yields:
<input type="button" id="42" value="Agregar" onclick="addrow(66,[2,4,6])" />
Which I think is what you want.
EDITED:
@Dustin Grahams suggestion to use json_encode is a good one. Replace the implode with:
$teams = json_encode($teamsarray);
And drop the extra brackets from the template.
Upvotes: 0
Reputation: 2086
It sounds like you might be looking for json_encode, so you might do something like this:
if (empty($teamsarray)) $teamsarray = array();
echo '<input type = "button" id = '.$buttonid.' value = "Agregar" onclick = "addrow(\'' . $leaguesarray[$numofleagues] . '\','.json_encode($teamsarray).'); return false;" />';
Upvotes: 1