Alex Massa Alex Massa - 1 year ago 36
Javascript Question

Pass php string as parameter for javascript function called in php script

So I have this serie of radio buttons generated by a php script that call a javascript function when they get clicked on:

$databases = mysqli_query($link, "SHOW DATABASES");
while($row = mysqli_fetch_row($databases)) {
$db = $row[0];
echo "<input type='radio' name='database' id='".$db."' onclick='displaydbcontent(".$db.")'>";

The javascript function then has to alert the content of the string:

function displaydbcontent(dbid) {
alert("This is a test");

Now, no matter what the content of the variable $db is, after displaying the first alert printing "This is a test", the second one always prints "[object HTMLInputElement]".

I am pretty sure that it's all a matter of quotation marks, but I don't see any way to work around it.

And for those who are wondering about it even thought it hasn't to do much with my issue, the $link variable has been initializated and works correctly.

Answer Source

Pass as argument which will return id property of the clicked-element


As you are passing $db as argument, it represents the element. Element with id becomes the global variables.

function callMe(elem) {
<script src=""></script>
<div id='elem' onclick='callMe(elem)'>Hello!!!!!</div>

Edit: Or wrap it in single quote, onclick='displaydbcontent("'.$db.'")'>";