div innerhtml not taking html - javascript

I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.

If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";

Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO

Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";

You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.

Related

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.
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>";
}
Are you adding a tag around your userName for JavaScript to work with?, i.e.
echo '<div id="userName">' . $userName. '</div>';
You are generating HTML/JS code on server side. Use double quotes around variable:
document.getElementById('userName').innerHTML="$date";
document.getElementById('userName').innerHTML='$userName';
document.getElementById('description').innerHTML='$desc';
document.getElementById('date').innerHTML='$date';

Unterminated string literal with PHP in JavaScript

Please tell me why this code tells me
SyntaxError: unterminated string literal
My code:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo $geladen; ?> ");
</script>
That's a JavaScript error message, which strongly implies one of two things:
the JavaScript that reaches the browser still includes the <?php etc., meaning the PHP didn't get parsed on the server (and thus the browser flipped out on "./testtext"), or
the file testtext (and therefore your variable $geladen) contains quotation marks. Either is possible from the very little information you have posted.
You can figure out which it is by looking at the HTML in your browser.
If it's the former (if you see <?php in the HTML), then you need to fix your server configuration.
If it's the latter (if testtext contains any " marks), then you need to encode it properly before echoing, using json_encode() like this:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?> ");
</script>
All that said, mixing PHP and HTML (not to mention PHP, HTML, and JavaScript) this way is not a great practice. You'd be much better off using a templating engine of some sort (Twig, Blade, etc.).
If the contents of 'testtext' contains a quote mark, it will break the javascript. Try addslashes().
<script>
console.log(" <?php $geladen = addslashes(file_get_contents("./testtext")); echo $geladen; ?> ");
</script>

JavaScript String Handling

I am passing a php value to javascript using onclick method, so it kind of looks like this
onclick="(method('<?php echo $variable; ?>'))"
But my problem is one of my values are "Ike's" , it contains a single qoute, which breaks the code. Any way in javascript to complete consider a passed parameter as a string,not anything else?
thanks
Your question seems to be more about PHP than Javascript, based on the code snippet you provided. Basically, you might want to escape the apostrophes with a backslash character.
onclick="(method('<?php echo $variable; ?>'))"
would then become something like this perhaps:
onclick="(method('<?php echo addslashes($variable); ?>'))"
... and please remove the parenthesis you have surrounding the onclick event, like so:
onclick="method('<?php echo addslashes($variable); ?>')"
You'll need to escape the string from PHP before passing it to Javascript. For example:
onclick="(method('<?php echo addslashes($variable); >'))"
If I understand well. I would prefer to use:
<div id="the_php_output">
<?php echo $variable; ?>
</div>
<input onclick="js_method()">
<script>
function js_method(){
$("#the_php_output").html();
}
</script>

Echoing HTML BODY variables from PHP to javascript

I am doing the following:
var test = <? echo $variable; ?>
and I want to append test:
$("#div").append(test);
My problem is that $variable might have '' or "" within it self. This means variable can be, for example
$variable = "<div style='some:style;'>Some test</div>"
So, when I put this in javascript it becomes
$("#div").append(<div style='some:style;'>Some test</div>)
without double quotes (throwing an error), which I try to improve:
$("#div").append("'"+<div style='some:style;'>Some test</div>+"'")
which won't work either way with ' ' or " " because it breaks the specials within the string fragment, stopping ' or "... can someone walk me through how this can be done?
EDIT
I'm sorry MY BAD my problem is that $variable actually has a function called inside, so that's how it becomes:
$("#div").append(<div onclick="some_function('string parameter')" style='some:style;'>Some test</div>)
That's it. How exactly can I do this?
Use json_encode:
$variable = json_encode("<div style='some:style;'>Some test</div>");
or with the function:
$variable=json_encode('<div onclick="some_function(\'string parameter\')" style="some:style;">Some test</div>');

Getting PHP data from MySQL DB inside script tag for use with Javascript

This is similar to PHP generated content inside Javascript breaking script, however I'm not able to understand where I'm wrong.
Here is the brief. I'm trying to output 10 strings from MySQL DB into a javascript array s, (s[1] to s[10]) (stored in one MySQL table under columns pt1 to pt1 - info so code is understandable to all). (Note $apos is just the apostrophe string - not a concern here).
<?php
echo "<script>\n";
echo "var s = [];\n";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$r['pt'.$i].$apos.";\n";
}
echo "</script>";
?>
It produces the right code when I look at the source by 'View Source' in browser:
<script>
var s = [];
s[1] = 'a';
s[2] = 'b';
.
.
s[10] = 'j';
</script>
However, this doesn't work as a script (meaning if I check in Google developer tools, and I click on content inside the 'script' tag elements, it is told to be 'text', and not 'script' in the bar below).
However if I remove the PHP, and manually write the whole script the same way, it works just fine. I have tried removing the \n linebreaks in the PHP code, but still the same problem.
Something in PHP is breaking the script. Can you help?
My best guess is that one (or more) of your strings contains a character (such as the apostrophe) which breaks the PHP output. Still the best solution was already prosposed by Passery in your comments section:
echo '<script>';
echo 'var s = ' . json_encode($info);
echo '</script>';
I think you may have been misreading the developer tools. When I look closely at Chrome, it does indeed identify your script as text, possibly because the default type is text/javascript. Putting an explicit type declaration on the <script> tag made no change.
However, when I add echo "alert('s[1]='+s[1]);"; after the for loop, the alert displays, and I am able to see the values of the other s[i] with the debugger.
In other words, I think your generated JavaScript worked all along.
I know you've already fixed the problem another way. I post this answer only in case it may help others.
Here is what I used for testing:
<?php
$a = "-abcdefghij";
$apos="'";
echo "<script type=\"text/javascript\">";
echo "var s = [];";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$a[$i].$apos.";\n";
}
echo "alert('s[1]='+s[1]);";
echo "</script>";
?>

Categories