Change the php variable to javascript

advertisements

I am new to php and javscript.I am working on some project of question and answer system.I want to send question id to javascript function.

here is my php code

<?php
if ($result->num_rows > 0)
{
    $i = 1;
    while($row = $result->fetch_assoc())
    {
        $p = $row["description"] ;
        echo '<div onclick="myOverFunction(<?= $p ?>)" align="left" class="j" role="group" aria-label="..."  >                                       <button id = "btnl<?=$i?>"  type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';
        echo $i;
        echo '</button>';
        echo '<p class="question" style ="display:inline; ">';
        echo $p;
        echo '</p>';
        echo '</div>';
    }
}
?>

My javacript function is:

<script>
function myOverFunction(x) {
    document.getElementById("demo").innerHTML = x;
    document.getElementById("btnl"+x).style.backgroundColor = "#d9534f";
}
</script>

my code does not working ..please help me ...


Your problem is:

echo '<div onclick="myOverFunction(<?= $p ?>)"

Change it to:

echo '<div onclick="myOverFunction('. $p .')".

Same goes for the other occurrences.
You can't echo from inside an echo

Your final echo should look like this:

 echo '<div onclick="myOverFunction(\''. $p .'\')" align="left" class="j" role="group" aria-label="..."  >                                       <button id = "btnl'.$i.'"  type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';

Note: If $p is a string, it needs quotes. And quotes inside quotes need escaping