Why my input field is Unexpected end. After PHP string concatenation? - javascript

In my PHP code, I echo a string that contains an input field with a javascript event. In this event, I assign a function where we pass 2 arguments. One is a number an another is a string.
Some this is wrong with my concatenation in function arguments. When I click on the input field I got this error
Uncaught SyntaxError: Unexpected end of input
Here is my code:-
<?php
$id = 6;
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo '<input type="checkbox" data-plugin-iso-switchx onchange="smtp_function('.$id.', "dfgdfg")">';
?>
<script>
function smtp_function(a, b){
alert('ok');
}
</script>
</body>
</html>

There's a problem with the " quotes inside the javascript part. Try this:
echo '<input type="checkbox" data-plugin-iso-switchx onchange="smtp_function('.$id.', \'dfgdfg\')">';
Here I use ' quotes instead of " and I escape them with a backslash.
In case the $id is not numeric it also needs quotes. You can do this to add those quotes:
echo '<input type="checkbox" data-plugin-iso-switchx onchange="smtp_function(\''.$id.'\', \'dfgdfg\')">';
All these quotes can become quite unreadable, so it might be better to use this:
$js = "smtp_function('$id', 'dfgdfg')";
echo '<input type="checkbox" data-plugin-iso-switchx onchange="'.$js.'">';
Note that variables inside double quotes are evaluated.

The problem is that you use twice ".
Try changing the type of quotation marks or using escape characters
I prefer to use ` when it is a text string because it does not interrupt line breaks
The following code works.
<?php
$id = 6;
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo '<input type="checkbox" data-plugin-iso-switchx onchange="smtp_function('.$id.', `dfgdfg`)">';
?>
<script>
function smtp_function(a, b){
alert('ok');
}
</script>
</body>
</html>
Hope this can help you.

Related

Unable to get button value with loop Jquery

I am working with jquery and PHP,I want to display "buttons" according to database value(dynamic) and want to get button values in jquery, I am using "input type hidden", But right now getting value="1"(static), But I want to get "correct" value (if I select button 2 then 2 value should get in jquery)
Here is my HTML code
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) { ?>
<button class="btn btn-scale btn-scale-asc-<?php echo $i; ?>">
<?php echo $i; ?>
<input type="hidden" <?php if($records['IsRatingQuestion']=="" || empty($records['IsRatingQuestion'])){ ?>name='ques_<?php echo $records['ques_id']; ?>' <?php } else{ ?>name='rangeR_<?php echo $records['ques_id']; ?>' <?php } ?> id="ratings" value="<?php echo $i; ?>">
</button>
<?php } ?>
Here is the script, Where I am wrong?
<script>
$(document).ready(function(){
$("#next1").click(function(){
var rating =$("#ratings").val();
alert(rating);
});
});
</script>
Before anything else, you need to remove input from inside that button. It's not a valid HTML.
Moreover, as mentioned in the comments, you cannot have the same id for all inputs, so I'd just remove it.
How about something like this:
$(document).ready(function() {
$('.item').each(function() {
var $button = $(this).find('button')
var $input = $(this).find('input')
$button.click(function() {
alert($input.val())
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<button>1</button>
<input type="hidden" value="1">
</div>
<div class="item">
<button>2</button>
<input type="hidden" value="2">
</div>
<div class="item">
<button>3</button>
<input type="hidden" value="3">
</div>
<div class="item">
<button>4</button>
<input type="hidden" value="4">
</div>
As far as I am understanding, you just want to show the value of the dynamic button using jquery. For this you just need to pass the value to the button using data attribute and then you can get the value using jquery.
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) {
echo '<button class="get-value" data-value="'.$i.'">Button '.$i.'</button>';
} ?>
<input type="text" id="show-value">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.get-value', function(){
var button_value = $(this).data('value');
$('#show-value').val(button_value)
});
});
</script>
I don't think putting an <input> inside of a <button> is valid html (although it seems to work?). Instead you can just assign those values as attributes of the button itself. Also ids have to be unique, so if you have a bunch of buttons with the same id, that is also invalid. I tend to stay away from ids and just use classes to avoid this.
Also, rather than having a bunch of choppy php, you can build a single string of html and echo it back all at once. By using double qoutes " on the outside of a string, you can use single quotes ' on the inside and drop variables right into the string without escaping or concatenating anything. Although you have to wrap associative arrays in brackets {} for it to parse correctly. PHP strings.
I'm guessing $name isn't a static variable, but without seeing the rest of your code, this is just an example:
<?php
$html = "";
$name = ($records["IsRatingQuestion"] == "" || empty($records["IsRatingQuestion"])) ?
"ques_{$records["ques_id"]}" :
"rangeR_{$records["ques_id"]}";
for($i = $records["start_range"]; $i <= $records["end_range"]; $i++) {
$html .= "<button class='btn btn-scale btn-scale-asc-$i ratings' name='$name'>$i</button>";
}
echo $html;
?>
$('.btn.ratings').on('click', function() {
//$(this).text() = $i
//$(this).attr('name') = $name
});

How to prevent PHP echo from ending a JS string?

I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Sign up page</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1>Sign up page</h1>
<form action="test.php" method="post">
<input placeholder="Enter your username" name="username"/><br/>
<input type="password" placeholder="Enter your password" style="margin-bottom:5px" name="password"/><br/>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
if(isset($_POST["username"],$_POST["password"],$_POST["submit"])){
if(mb_strlen($_POST["username"])<8){
?>
<script>
alert("Your username must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[0];
i.value="<?php echo $_POST['username']; ?>";
i.focus();
</script>
<?php
}else if(mb_strlen($_POST["password"])<8){
?>
<script>
alert("Your password must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[1];
i.value="<?php echo $_POST['password']; ?>";
i.focus();
</script>
<?php
}else{
echo "Successfully signed up!";
}
}
?>
</body>
</html>
It works fine most of the time, but if you try entering ";f(); into the username field, you get an error in the console and no alert.
As is clearly visible, that is happening because when PHP receives the input, it echoes it in the JS string. "; ends the string and the statement, while f(); causes an error which prevents the input from focusing. This occurred under 8 characters, therefore causing it to fall under mb_strlen($_POST["username"])<8.
Usually I would just use htmlspecialchars, but if you try adding that, then if you put ";<!--, it comes out with < instead of <. Some users may want < (or other &*; characters) in their username, and (if they weren't developers) would be surprised what < means.
So how do I prevent the JavaScript Injection from occurring while still keeping User Friendliness?
You should be using json_encode to output your values (and note you no longer need the enclosing "s):
i.value=<?php echo json_encode($_POST['username']); ?>;
This will ensure that quotes within the string are escaped and the entire value is treated by JavaScript as a string. For your example data, this will produce
"\";f();"
The problem is the double-quote in this example. Try addslashes:
i.value="<?php echo addslashes($_POST['username']); ?>";
Though Nick's answer may be better for JS. I'm more PHP than JS.
You should never inject unsanitized code into anything. This can cause XSS attacks at the least.
I think the easiest way to sanitize your code while keeping the user friendliness would be to use json_encode()
<?php
}else if(mb_strlen($_POST["password"])<8){
$data = json_encode(['password' => $_POST['password']]);
?>
<script>
alert("Your password must be at least 8 characters long.");
var user_data = <?php echo $data; ?>;
var i=document.getElementsByTagName("input")[1];
i.value=user_data.password;
i.focus();
</script>
However!
You should really be putting this in the Input element:
<input type="password" value="<?=htmlspecialchars($_POST['password'] ?? '',ENT_QUOTES); ?>" placeholder="Enter your password" style="margin-bottom:5px" name="password"/>

Pass PHP Date variable to Javascript Function

I have a php date created with the code:
$date = date("d-m-Y");
I can echo this date out with:
echo $date;
and that works fine. But I want to pass this to a javascript function onClick of a button on my page. So I have:
<input type="button" onClick="myFunction(<?php echo $date; ?>)" value="Today">
Pretty standard. But when I alert the function in javascript:
function myFunction(phpDate) {
alert(phpDate);
}
it then gives me:
-2018
in an alert box.
Full code
For anyone wondering, here is my full code:
<?php
$date = date(d-m-Y);
echo $date; // to test date is working (it is)
?>
<script type="text/javascript">
function myFunction(phpDate) {
alert(phpDate);
document.getElementByID("dateField").valueAsDate = phpDate;
// can someone please tell me if ^^^this^^^ line above is correct syntax wise.
// I'm particularly concerned with '.valueAsDate'.
}
</script>
<html>
<input type="date" id="dateField">
<input type="button" onClick="myFunction(<?php echo $date; ?>)" value="Today">
</html>
BTW I do have <!doctype html> and <head> and <body> tags in there. So my page works.
You are actually passing the date as Number (2 - 1 - 2019 = -2018 for example), not as a String. You will need to wrap the date value in single quotes
<input type="button" onClick="myFunction('<?php echo $date; ?>')" value="Today">

Trying to pass multiple parameters from php to javascript

Heres my current code in php with one parameter which works
<?php
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.')">';
?>
Now im trying to pass two parameters or more, but cant seem to get it to work, here is my attempt:
<?php
$name="abc
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.','.$name.')">';
?>
You need quotes around the parameters or javascript treats them like variables instead of strings.
echo '<input type="button" value="Submit" onclick="changeConfirmed(\''.$sid.'\',\''.$name.'\')">';
If one of your JavaScript function parameters is a string, you'll have to correctly enclose it in quotes:
<?php
$name="abc";
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.',\''.$name.'\')">';
?>
You get away with $sid not enclosed in quotes because it looks like a number.

Using PHP variables as parameters for JavaScript function

I'm having a bit of trouble working with the quotations for this. So, let's make an example of sending two strings we want concatenated through variables, and then running them through a JavaScript function to concatenate them (I understand that this is very basic in PHP and I know how to do it, I'm just using this example for the sake of simplicity).
JavaScript Code:
function con(first, last) {
answer = first+last;
alert(answer);
return;
}
HTML and PHP:
<?php
$first = "Butter";
$last = "Last";
echo '<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />';
?>
This code above does not work, how can I make it work?
Thanks all
If you have a look at the html that that's generating it will be something like this:
<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />
Which as you can see is not correct.
There are a couple of issues with your code, first of all, variables names, like $first won't get evaluated to their value if they are inside single quotes.
Try:
echo '<input type="button" value="Get Answer" onclick="con("'.$first.'", "'.$last.'")" />';
This will output :
<input type="button" value="Get Answer" onclick="con("Butter", "Last")" />
which is still not correct, as you're not passing the arguments to your javascript function correctly.
Try:
echo '<input type="button" value="Get Answer" onclick="con(\''.$first.'\', \''.$last.'\')" />';
which should output
<input type="button" value="Get Answer" onclick="con('Butter', 'Last')" />
that hopefully works :)
Here is your solution
JavaScript Code:
function con(first, last) {
answer= first+last;
alert(answer);
return;}
PHP and HTML code:
<?php
$first = "Butter";
$last = "Last";
echo '<input type="button" value="Get Answer" onclick=con("'.$first.'","'.$last.'") />';?>
when you pass the value to the javascript function through php you must pass the value in 'single quote' or "double quote" like onclick=con("'.$first.'","'.$last.'");

Categories

Resources