Javascript not changing html content - javascript

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';

Related

set value in javascript with using echo in php page

I've already retrieved a variable from user input in PHP and want to use as default value in another form as it's gonna displayed as follow:
$username = sanitizeFormUsername($_POST['username']);
echo'<script>document.getElementById("loginUsername").value ='.$username.' </script>';
but it's not working. kindly advise me on how to set a value of an element with a PHP variable in PHP page. Thank you
PHP is a templating language, and it has a nice shortcut for echo. Why not take the advantage of it? You don't need that JavaScript at all, instead, do something like this with PHP:
<?php
$username = sanitizeFormUsername($_POST['username']);
?>
<!DOCTYPE html>
...
<input id="loginUsername" value="<?=$username?>">
short answer : interchange single quote(') and double-quote(")
<input type="text" id='loginUsername'>
<?php
$username = "abc";
echo"<script>document.getElementById('loginUsername').value ='$username'</script>";
now it will work fine.
long answer: in PHP
$abc = 'qwerty/' . $name;
and
$abc = "qwerty/$name";
are same.
from PHP official website ( https://www.php.net/manual/en/language.types.string.php)
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

How to pass multidimensional array from PHP to Javascript?

I am trying to get array value from JSON string, and I do the work with json_decode PHP.
<?php
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
$jsonDecoded=json_decode($jsonContent,true);
foreach($jsonEncoded['BMS'] as $p){
echo '
ID: '.$p['id'].'
Tipe: '.$p['type'].'
';
echo "<br>";
?>
The PHP code works, and give the result of array from JSON string.
And this is my Javascript code
<script>
var bmsdata = <?php echo $jsonDecoded ?>;
alert(bmsdata["1"].id); // For check, i want to see the id of row 1
</script>
But nothing was shown up.
Am i doing right so far? Or i missing something to pass the value from PHP to Javascript? Any suggestion will be appreciated.
$jsonDecoded is the decoded json.
Please change
var bmsdata = <?php echo $jsonDecoded ?>;
to
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
or use the already exisiting variable $jsonContent:
var bmsdata = <?php echo $jsonContent; ?>;
This one should work, as I lookup JSON at http://megarkarsa.com/gpsjson.php ;)
<script>
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
alert(bmsdata.BMS["1"].id); // For check, i want to see the id of row 1
</script>
You just forgot 'BMS' key ;)
Looks like you're injecting a decoded, PHP-representation of the data into your javascript. You probably (if you want to continue doing it this way) want to echo the encoded version (jsonContent) instead.
Ultimately, you might want to rethink the approach. Fetching the data via ajax is often an easier way to work with it, since you don't need to worry about writing bare javascript via php, which has all sorts of escaping issues to get right.

div innerhtml not taking html

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.

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>";
?>

using php to provide a variable in an onclick event

I am trying to pass a variable through the onclick function into javascript.
So I am trying to pass
onclick = "purchase_song(<?php echo $row['filename']; ?> , <?php echo $row['price'] ?> )"
note the function works fine if I pass it a non php variable
onclick = "purchase_song( 'filename' , 1)"
And I use a similar technique to pass variables through hyperlinks and the GET function. Is it not possible to use PHP inside a javascript onlick? If so, what am I doing wrong.
Thanks,
If the values are valid strings then you are doing everything right except one thing : to pass php input as a string argument to the javascript function you should wrap it in single quotes ':
onclick = "purchase_song('<?php echo $row['filename']; ?>' , '<?php echo $row['price'] ?>')"
The values should need to be quoted.
onclick="<?php printf("purchase_song('%s', '%s')", $row['filename'], $row['price'] ?>"
This example uses printf as its easer to see what the output from the format string.

Categories