Home > OS >  Javascript not changing html content
Javascript not changing html content

Time:01-20

I am trying to use innerHTML of javascript in order to edit html elements but it isn't working as it should. The code:

if($postSQL->num_rows > 0){
                                $postSQL->bind_result($userID,$userName, $postID, $desc, $image, $date);
                                $postSQL->fetch();
                                echo $userName."".$desc."".$date."".$image;
                                echo "<script>
                                    document.getElementById('userName').innerHTML=$userName;
                                    document.getElementById('description').innerHTML=$desc;
                                    document.getElementById('date').innerHTML=$date;                                 
                                 </script>";
                            }

I noticed that when I try to change 'userName' using an int type variable, it works. So if I do like this:

document.getElementById('userName').innerHTML=$date;

It works but it won't do the same for string type variables.

CodePudding user response:

The issue here is strings need quotes to work properly. Assume for a moment that $userName equals John. That PHP code is going to display

<script>
document.getElementById('userName').innerHTML=John;
...
</script>

However this is incorrect JavaScript, because all strings should be surrounded by quotes. So to fix your code, just add quotes around the values you want, such as

if($postSQL->num_rows > 0) {
    $postSQL->bind_result($userID,$userName, $postID, $desc, $image, $date);
    $postSQL->fetch();
    echo $userName."".$desc."".$date."".$image;
    echo "<script>           
        document.getElementById('userName').innerHTML='$userName';
        document.getElementById('description').innerHTML='$desc';
        document.getElementById('date').innerHTML='$date';
    </script>";
}

CodePudding user response:

Are you adding a tag around your userName for JavaScript to work with?, i.e.

echo '<div id="userName">' . $userName. '</div>';

CodePudding user response:

You are generating HTML/JS code on server side. Use double quotes around variable:

document.getElementById('userName').innerHTML="$date";

CodePudding user response:

document.getElementById('userName').innerHTML='$userName';
document.getElementById('description').innerHTML='$desc';
document.getElementById('date').innerHTML='$date';      
  • Related