0

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.

1
  • show us your SQL data and also the html. hard guess, parse the date or simply try ='hello world' isntead of $date to narrow down if the issue is the variable or not. Commented Jan 20, 2023 at 11:37

4 Answers 4

1

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.