Possible Duplicate:
How to pass a PHP variable to Javascript?
I need to somehow make this function to accept parameter.
index.html
function dataOut(name2) {
var names = name2.value;
document.getElementById("output2").innerHTML = names;
//even document.getElementById("output2").innerHTML= "blablabla";
//just to show that it works
}
And the function will be called from :
dbase.php
...
echo "<td><a href='javascript:dataOut(this.value)'>" . $row['FirstName'] . "</a></td>";
...
I dont have problem on displaying the the table. The link does show with their respective "$row[‘FirstName’]" which are string from database. I tried to use non-parameter function:
function dataOut(){}
echo "<td><a href='javascript:dataOut()'>" . $row['FirstName'] . "</a></td>";
and these work fine.
If i try to pass parameter, the function will not do anything; not even if i just want to print random string as in the commented section of the function. If i hover my mouse on the link created within that table i see:
javascript:dataOut(firstname)
//where first name is the value of the $row['FirstName']
Alternatives that i tried:
echo "<td><a href='javascript:dataOut(this.value)'>" . $row['FirstName'] . "</a></td>";
echo "<td><a href='javascript:dataOut($row['FirstName'])'>" . $row['FirstName'] . "</a></td>";
echo "<td><a href='javascript:dataOut('" . $row['FirstName'] .'")'>" . $row['FirstName'] . "</a></td>"; //this give me undefined variable error
echo "<td><a href='javascript:dataOut(". $row['FirstName']. ")'>" . $row['FirstName'] . "</a></td>"; // this no error
Any help would be appreciated. More over i tried also <a onclick=dataOut ....> which doesnt work either.
You shouldn’t try to create JavaScript strings by concatenating quotes and plain strings. Use
json_encode()instead which is guaranteed to output a valid JavaScript expression:On a side-note, using
javascript:urls is generally a bad idea. Better useonclick="dataOut(...); return false;"instead and use a useful href value or#if no proper URL for people without JavaScript exists. Of course it would be even better to register the event properly instead of using an inline event, and storing the data in adata-attribute but this would be even more off-topic here.