set value in javascript with using echo in php page - javascript

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.

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>

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.

Categories