Quotes error when passing php string value to javascript onClick - javascript

I want to passing variable from php to Javascript. But it can only passing integer type. When I pass value that is not integer, the variable value is undefined.
<?php
$sqlCall="SELECT * FROM table";
$resCall=mysqli_query($con, $sqlCall);
while($row=mysqli_fetch_array($resCall)){
echo "<tr>";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[name]."</td>";
echo "<a onclick='edit(".$row['id'].",'".$row['name']."')'>Edit</a>"
?>
and here is my JavaScript:
<script>
function edit(id, name){
document.getElementById('edit_id').value = id;
document.getElementById('edit_name').value = name;
}
</script>

The problem comes from the single quotes ' use " instead like :
"<a onclick='edit(".$row['id'].","".$row['name']."")'>Edit</a>"

Related

syntaxerror: expected expression, got '}' in php and javascript

I have a select option and when I select an option it must show my colors
Look at my codes
<?php foreach ($colors as $color) { ?>
<option onclick=addColor("<?php echo $color->title ?>", this) value="<?= $color->id ?>"><?= $color->title ?></option>
<?php } ?>
script
function addColor(color_name, tag) {
var optionTag = $(tag);
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">+color_name+</span>';
var divRow = optionTag.parents('.row');
divRow.append(selectColor);
}
but i get this error.
SyntaxError: expected expression, got '}'
Try
PHP
You are not defining the end and beginning of your onclick attribute, enclose it with " " as you also need a string parameter to your method enclose it with ' ' as to not terminate the attribute string prematurely.
<option onclick="addColor('<?php echo $color->title ?>', this)" value="<?= $color->id ?>"><?= $color->title ?></option>
Javascript
Terminate your string around the variable to indicate that the variable is to be appended to the string. If you just write + var + inside a string that will be a normal part of the string.
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">'+color_name+'</span>';
You are also mixing output methods in your PHP, I would recommend sticking to one kind of make it easier to read your code.

Referencing a defined html variable in JS

My index.php page includes a config.php file, which returns an array that I have defined some variables in by using "define('var1' , 10)".
I am trying to validate my forms input, but I can't figure out how I can reference var1 from within the JS function. What is the easiest way to do this?
Just echo it to a javascript variable:
<script type="text/javascript">
var var1JS = "<?php echo $var1; ?>";
</script>
Not quite sure I am full understanding without seeing the code but, you could echo the variable from the PHP array in the JS function (as above answer).
Or Echo the entire JS query:
$y = count($PHPdata_array);
echo "function exampleFunction() {";
echo "var ArrayName = [";
for ($i = 1; $i <= $y; $i+=2) {
echo "{" . $PHPdata_array[$i] . "," . $PHPdata_array[$i-1] . "},";
}
echo "];";

javascript function doesn't work in php

I want to call a JavaScript function inside PHP code,This function return a number, the Result for example is : http://localhost/1.php?id=fn(3)
as you see this function cannot be interpreted by the browser I already tried ' ' or " " But I get the same problem, normally I must receive for example http://localhost/1.php?id=3
Any help on this problem would be greatly appreciated! Thank you in advance!
<body>
<script type="text/javascript">
function fn(a)
{
var table = document.getElementsByTagName("table")[0];
var res=table.rows[a].cells[0].innerHTML;
return res;
}
</script>
<table class="table " id="tableId">
<?php
$bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$reponse = $bdd->query('SELECT * from jeux_video');
while ($donnees = $reponse->fetch()){
echo "
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
";
?>
<td id="td1"><?php echo $donnees['ID']?></td>
<td><?php echo $donnees['nom']?></td>
<td><?php echo $donnees['possesseur']?></td>
<td><?php echo $donnees['prix']?></td>
</tr>
<?php } $reponse ->closeCursor(); ?>
</table>
</body>
The string you're putting on the href won't be parsed as a javascript expression, but just as a string.
You need to output a valid javascript statement for the fn call to execute:
echo "<tr onclick=\"location.href='1.php?id=' + fn(".$donnees[ID].")\">";
This will output:
<tr onclick="location.href='1.php?id=' + fn(3)">
PHP runs on the server, and Javascript on the client. That's the rule. If you want PHP to output a value anywhere in your document, you need to do it with PHP:
echo "<tr onclick=\"location.href='1.php?id=' + fn(" . $donnees[ID] . ")'\">"; // ...
As it is, this is likely the exact markup that is being output:
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
Which, to Javascript, makes no sense.
This doesn't do what you think it does:
location.href = '1.php?id=fn(3)'
JavaScript isn't going to automatically evaluate code inside of a string. You have to execute the code itself and concatenate its result to the string. Something like this:
location.href = '1.php?id=' + fn(3)

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.

.replace() not working inside a jQuery function

I don't understand why replace() function doesn't work into my jQuery function:
jQuery(document).ready(function($){
var amount_min = <?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>;
var amount_min = amount_min.replace(/[^\d]/g, "");
$('input[name=amount]').val(amount_min);
});
Whatever input I give (for example "100ab" or "10.000") it doesn't replace it with "100" or "10000".
How to do?
You forgot to put double-quotes.
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo 0; ?>";
Because, replace works in Strings.
UPDATE #1
If for any religious reason you don't want to wrap the PHP in double quotes then output them along with the number.
var amount_min = <?php echo '"' . ($_GET['amount_min'] ? $_GET['amount_min'] : 0) . '"'; ?>;
UPDATE #2
Compulsory validation you can use:
var amount_min = <?php echo '"' . (int)($_GET['amount_min']) . '"'; ?>;
can you please try this:
$(document).ready(function(){
var amount_min = "<?php if($_GET['amount_min']){ echo $_GET['amount_min'];}else{ echo '0';} ?>";
console.log("original-> "+amount_min);
var amount_min = amount_min.replace(/\D/g,'');
console.log("replaced-> "+amount_min);
});
Your PHP code is outputting a number:
var amount_min = 100;
Since you're expecting a string, wrap it in quotes:
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>";
I haven't touched PHP in years, but I think you could simplify your code a little:
var amount_min = "<?php echo($_GET['amount_min'] || '0'); ?>";
Also, why don't you just fetch the GET parameter with JavaScript?
You don't need the .replace() code (it also only works on strings); PHP can already do the proper conversion for you:
$(function() {
var amount_min = <?php echo isset($_GET['amount_min']) ? (int)$_GET['amount_min'] : 0; ?>;
$('input[name=amount]').val(amount_min);
});
You could also use filtering for this:
<?php echo filter_input(INPUT_GET, 'amount_min', FILTER_VALIDATE_INT, array('options' => array('default' => 0))); ?>
Note that filter_input would not accept a value like 100abc, so use wisely.
If you still want to use strings safely in JavaScript you should use json_encode().
Btw, any answer that involves an unmodified echo of a request variable from PHP inside JavaScript code is wrong and can cause XSS attacks! You have been warned.
Update
The regular expression based replacement can also be done in PHP:
var amount_min = <?php echo (int)preg_replace('/\D+/', '', isset($_GET['amount_min']) ? $_GET['amount_min'] : 0); ?>;
Since all non-digits are removed, you can safely apply the (int) cast.

Categories

Resources