Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript not changing html content

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading