Quote is breaking the syntax even after escape - javascript

I have a button who should call an action with 2 parameters (an integer and a String). I m using Yii2.
<button class="button_answer"
onclick="submitAnswer(
<?php echo $id ?>,
<?php echo '\''.Html::encode($title).'\''?>
);">
Submit your answer
</button>
it is working, but when the parameter title contains a single quote or a double quote, the syntax is broken.
I become something like this:
<button class="button_answer" onclick="submitAnswer(214, 'What's the ...?');">
Post your answer
</button>
I dont know how to solve this.

You need to encode the PHP string for JavaScript. Then you need to encode the JavaScript for HTML.
<?php
$js_string_title = json_encode($title);
$js = "submitAnswer($id, $js_string_title)";
$html_safe_js = htmlspecialchars($js);
?>
<button class="button_answer"
onclick="<?php echo $html_safe_js; ?>">
Submit your answer
</button>
A nicer approach would be to avoid inlining the JS altogether:
<button class="button_answer"
data-id="<?php echo htmlspecialchars($id); ?>"
data-title="<?php echo htmlspecialchars($title); ?>">
Post your answer
</button>
Along with something like:
addEventListener("click", answer_handler);
function answer_handler(event) {
var el = event.target;
if (el.classList.contains("button_answer")) {
submitAnswer(el.dataset.id, el.dataset.title);
}
}

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
});

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

Pass ID on onClick Function in Javascript

I am trying to pass the email using the onClick function and I want to show that email in alert:
<td>
<button class="btn btn-primary" name="buton" onclick="myfunction(<?php $email; ?>)" >Edit</button>
</td>
Here is my function:
<script type="text/javascript">
function myfunction(id)
{
alert(id);
}
</script>
You've to make two changes to validate your code :
You should add echo to pass the php variable to JS.
You need to add single quotes since the $email is a string and you've already using double quotes in onclick attribute.
<td>
<button class="btn btn-primary" name="buton" onclick="myfunction('<?php echo $email; ?>')" >Edit</button>
</td>
try this
when you are passing the email(String) it should be in quote and while using php in javascript in this case u have to use echo
<td><button class="btn btn-primary" name="buton" onclick="myfunction('<?php echo $email; ?>')" >Edit</button></td>
What you want is probably the PHP tag <?= that echoes the $email variable as an argument to the JavaScript function. Note that you will need quotation marks for the email:
onclick='myfunction("<?= $email ?>")'
If shorttags are not enabled the long version must be used:
onclick='myfunction("<?php echo $email; ?>")'
echo the variable in the php tag
<td><button class="btn btn-primary" name="buton" onclick="myfunction('<?php echo $email; ?>')" >Edit</button></td>
Your code is working, you are just not echoing the value of $email in a good way:
- Lack of the single quotes in myfunction(' … ')
- Lack of echo inside your php tags myfunction('<?php echo $email ?>')
To avoid that kind of problems…
In your php, I suggest you to use heredoc syntax:
echo <<< EOD
<td><button class="btn btn-primary" name="buton" onclick="myfunction('{$email}')">Edit</button></td>
EOD;
Note the { } around the variable. They are not necessary, but I suggest you to use them, as they make the variables more noticable.
⋅ ⋅ ⋅
The result will be:
function myfunction(id) {
alert(id);
}
<td><button class="btn btn-primary" name="buton" onclick="myfunction('myemail#stackoverflow.com')">Edit</button></td>
Documentation about Heredoc syntax: http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
I hope it helps.
function myfunction(id)
{
alert(id);
}
<td>
<button class="btn btn-primary" name="buton" onClick="myfunction('<?php echo $email; ?>')" >Edit</button></td>
You need to put the email in 'single quotes'

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.

send php post variable to url using javascript when button is clicked

I have a php page which gets $page and $user using post method, I also have a button that i want, to open a URL in the same window using $page and $user variables when clicked, to use them with $_GET[] function.
i want my URL be like:
http://www.test.com/test.php?page=$page&user=$user
my code is like this:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
<html>
<head>
function openurl() {
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
}
</head>
<body>
<button onclick="openurl()" type="button">open url</button>
</body>
</html>
There is no need for scripting at all
If you want GET:
<?php
$page=$GET_['page']; // should be sanitized and you can use REQUEST for either
$user=$GET_['user'];
$parm = "page=".$page."&user=".$user;
?>
Open URL
If you need to post:
<form action="test.php" method="post">
<input type="hidden" name="page" value="<?php echo $page; ?>"/>
<input type="hidden" name="user" value="<?php echo $user; ?>"/>
<input type="submit" value="Open URL" />
</form>
Change these lines:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
....
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
to this:
<?php
$page=$_POST['page']; //incorrect $_POST declaration
$user=$_POST['user']; //incorrect $_POST declaration
?> //php tag incorrectly closed
....
var user=<?php echo $user;?>; //echoing a variable not string (no need for quotes)
var page=<?php echo $page;?>; // echoing a variable not string (no need for quotes)
open('www.test.com/test.php?page='+page+'&user='+user,'_self'); // link was broken, forget to put '+' after page variable in link.
You can create a form and via Javascript just run YOURFORMNAME.submit();
Use href in javaScript to move to another location:
location.href="www.test.com/test.php?page='+page'&user='+user"

Categories

Resources