quick question about onclick - javascript

Can i do like this:
<a href="#" id="thelink" onclick="window.parent.OpenVote("<? echo $_GET['id']; ?>", '<? echo $rowData['username']; ?>');">
It doesnt seem to work..

You can, but you need to use single quotes to pass an argument or else you'll escape the onclick attribute.
<a href="#" id="thelink" onclick="window.parent.OpenVote('<? echo $_GET['id']; ?>', '<? echo $rowData['username']; ?>');">

The first issue is the quotes inside the value for the onclick attribute. You either have to html encode them using " or use apostrophes instead:
<a href="#" id="thelink" onclick="window.parent.OpenVote('<? echo $_GET['id']; ?>', '<? echo $rowData['username']; ?>');">
Then you have to consider the values that you put in the code.
First you have to encode the values so that they can be string literals in the Javascript code. If there can be any backslash characters in them, you have to replace them by double backslashes, then if there can be any apostrophes in them, you have to escape them by putting a backslash before them (i.e. replace each apostrophe with a backslash and an apostrophe).
Then you have to encode the Entire script so that it can be a value in an HTML tag. As there are no characters that need escaping in the static code, you only have to encode the values that you put in the code. You have to HTML encode the values so that any characters like <, >, & and " are replaced with HTML entities.

Probably due to extra quotes in the onclick statement.
Try replacing the double quotes around the id param with single quotes:
<a href="#" id="thelink" onclick="window.parent.OpenVote('<? echo $_GET['id']; ?>', '<? echo $rowData['username']; ?>');">

Related

How do I add a php variable to a onclick function argument?

Beginner JS here.
I am trying to add a PHP variable to a Javascript onclick function. I converted the PHP variable to a JS variable just fine. However, when adding the JS variable to the function I'm not receiving the desired output. What am I doing wrong?
<script>
js_logo_number = "<?php echo $logo_number; ?>";
</script>
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(js_logo_number)">
You can do like this :
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(<?php echo $logo_number; ?>)">
This code works for me. Be sure you use a let or const (or the outdated var) prefix to declare js_logo_number a new variable. Also make sure that $logo_number is set like this:
<script>
let js_logo_number = <?php isset($logo_number)?$logo_number:null; ?>;
</script>
Then make sure you convert it to an integer in Javascript, if that's how you want to use it:
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
let js_logo_number = "5";
function openModal(){
console.log('openModal fired');
}
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
<img src='https://placekitten.com/200/200' onclick="openModal();currentSlide(js_logo_number)">
When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
See: PHP tags
1) echo
<?php echo 'if you want to serve PHP code in XHTML or XML documents, use these tags'; ?>
Solution:
<img src='<?php echo $image_src ?>'
onclick="openModal();currentSlide(<?php echo $logo_number ?>)">
2) Short echo
You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.
Solution:
<img src='<?= $image_src ?>'
onclick="openModal();currentSlide(<?= $logo_number ?>)">
3) If short_open_tag is enabled
<? echo 'this code is within short tags, but will only work '
.'if short_open_tag is enabled'; ?>
Solution:
<img src='<? echo $image_src ?>'
onclick="openModal();currentSlide(<? echo $logo_number ?>)">
See: PHP tags

How do I use PHP to encode a string containing quotes to make it safe for inline 'onclick'?

I have a variable in a database that could potentially contain single or double quotes. When I retrieve the variable from the database, it is written with PHP into an inline "onclick" hander:
echo '<li><a onClick="a4e.duplicate_assignment('.$this_assignment['id'].',\''.htmlspecialchars($this_assignment['title'],ENT_QUOTES).'\',\'/assignments/'.$type.'/\');" href="javascript:void(0);">';echo '<i class="fa fa-copy"></i> Duplicate assignment</a></li>';
This produces HTML that looks like this in the page source:
<li><a onClick="a4e.duplicate_assignment(92,'ELLLO - 'If I had a million dollars'','/assignments/cloze/');" href="javascript:void(0);"><i class="fa fa-copy"></i> Duplicate assignment</a></li>
However, clicking the link produces the following error in the console:
Uncaught SyntaxError: missing ) after argument list
I thought using the PHP function "htmlspecialchars" would mitigate this issue, but it doesn't seem to work.
Any help greatly appreciated.
P.S. It is not possible in this case to use a Javascript "onclick" handler - it has to be inline HTML. Also, it is not possible to ban the use of quotation marks in the variable value.
Try using the function:
addslashes()
EDIT: This method will take care of the quotes in the string itself, but may not be suitable if you need to retain quotes for HTML insertion. Read the docs carefully.
http://php.net/manual/en/function.addslashes.php
its because your Unicode (') is also being treated as '
use this
<li><a onClick="a4e.duplicate_assignment(92,'ELLLO - \'If I had a million dollars\'','/assignments/cloze');" href="javascript:void(0);"><i class="fa fa-copy"></i> Duplicate assignment</a></li>
Use json_encode to convert a value to a JavaScript literal (with all necessary escaping).
Use htmlspecialchars to convert a value (such as a JavaScript program) to something safe to place in an HTML attribute value.
$id = $this_assignment['id'];
$title = $this_assignment['title'];
$url = "/assignments/$type/";
$js_id = json_encode($id);
$js_title = json_encode($title);
$js_url = json_encode($url);
$js = "a4e.duplicate_assignment($js_id, $js_title, $js_url);
$html_js = htmlspecialchars($js, ENT_QUOTES);
?>
<li>
<a href="javascript:void(0);" onclick="<?php echo $html_js; ?>">
<i class="fa fa-copy"></i>
Duplicate assignment
</a>
<li>
A better approach would be to use progressive enhancement and non-inline JS. You've ruled that out, but you should try to remove that restriction.
$id = $this_assignment['id'];
$title = $this_assignment['title'];
$url = "/assignments/$type/";
$html_id = htmlspecialchars($id, ENT_QUOTES);
$html_title = htmlspecialchars($title, ENT_QUOTES);
$html_url = htmlspecialchars($url, ENT_QUOTES);
?>
<li>
<a href="<?php echo $html_url; ?>" data-title="<?php echo $html_title; ?>" data-id="<?php echo $html_id; ?>">
<i class="fa fa-copy"></i>
Duplicate assignment
</a>
<li>
<!-- and later -->
<script>
document.querySelector("a").addEventListener("click", duplicate_assignment_handler);
function duplicate_assignment_handler(e) {
e.preventDefault();
a4e.duplicate_assignment(this.dataset.id, this.dataset.title, this.href);
}
</script>
</script>

How can I use HTML code to print it in PHP?

I want to use this HTML code and print it in PHP.
In the HTML code I use this:
<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>');">View</button>
How should it be used it in PHP?
I've tried this code:
echo '<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/$test.jpg\'></img>');">View</button>';
But unfortunately, this is not working.
you mix up your quotes
if you use ' quotes in the echo statement, you cannot use them (or have to escape them) in the string
the best solution here is escape the single quotes in your string, so they don't mark the end of the echo command
echo('<button onMouseover="htmlcode(\'<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>\');">View</button>');
If you want to use it in some kind of an if statement then you can go for this:
<?php if( /*your condition*/ ) :?>
<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'> </img>');">View</button>
<?php endif; ?>
Note this way you can write long snippets of html easily, which is not the case with echo.
If this is not conditional, then just do something like this:
<?php // some php code
// some more php
?>
<html>
Your html here
</html>
<?php // next section of php
// more php
?>
The parts between the php sections will be outputed just as if they were put into an echo statement.
If you want to see the html in the browser then you can use.
print htmlspecialchars("<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>');">View</button>")

inserting popup window command in sql

I'm assigning popup window on my links but it doesn't work sorry i'm still learning about mysqli and javascript.
while($row = mysqli_fetch_array($result))
{
$id = $row['BapID'];
echo "<tr>";
echo "<th>" . "<a href=bapview.php?BapID=$id onlick='pop_up(this);'>View Full Info</a>" .
" | " .
"<a href=bapupdate.php?BapID=$id onlick='pop_up(this);'>Edit</a>" . "</th>";
My script
function pop_up(url){
window.open(url,'win2','status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=1076,height=768,directories=no,location=no') }
The url that you want the pop-up window to point should be put as the parameter to your function call in your onclick handlers:
<a onclick="pop_up('bapupdate.php?<?php echo $id; ?>');">Edit</a>
As you can see at
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
the first parameter to the window.open method is a string value for the url you want the opening window to point to. Your code was attempting to provide as that argument the actual reference to the link element on your page (that's what this will refer to in that context).
A couple of suggestions:
Don't be afraid to 'exit' (?>) PHP half way through a script. This will make it easier to read later on and allows you to write in pure HTML.
It looks like your missing you quotation marks around your href parameter. This likely won't cause issues but you never know. I would also recommend using the full url in your href and also as your pop_up() parameter (as suggested by #myesain)
<?php
while($row = mysqli_fetch_array($result)){
$id = $row['BapID']; ?>
<tr>
<th>
<a href=# onclick='pop_up("http://fullurl.com/bapview.php?BapID=<?php echo $id; ?>");'>View Full Info</a>
|
<a href=# onclick='pop_up"http://fullurl.com/bapupdate.php?BapID=<?php echo $id; ?>");'>Edit</a>
</th>
</tr>
<?php
//Rest of code
?>

Html with javascript in php seems to be conflicting

The code i want to get into a php statement is
<a href="javascript:void();"
onclick="document.loginfrm.user.value="username";
document.loginfrm.pass.value="password";
document.loginfrm.submit();">login
</a>
So what i would normally do is just surround it with an echo and quotation marks: an then replace any quotation marks in the statement with these --> ('), so that's what i did... and for some reason it seems to misinterpret the sentence severely. Here is the code i enter in php.
echo "<a href='javascript:void();'
onclick='document.loginfrm.user.value='username';
document.loginfrm.pass.value='password';
document.loginfrm.submit();'>". login ."</a>";
And this is how the browser interprets it:
<a href="javascript:void();
" onclick="document.loginfrm.user.value=" username';=""
document.loginfrm.pass.value="password" ;="" document.loginfrm.submit();'="">
login</a>
So yes is there any way around displaying html within php that could get around this problem
Can you try this, added \
echo "<a href=\"javascript:void();\"
onclick=\"document.loginfrm.user.value='username';
document.loginfrm.pass.value=password';
document.loginfrm.submit();\">login </a>";
You need to escape it properly. Try
echo "<a href=\"javascript:void();\"
onclick=\"document.loginfrm.user.value='username';
document.loginfrm.pass.value='password';
document.loginfrm.submit();\">". $login ."</a>";
You're not escaping your quotes. Try:
echo "<a href=\"javascript:void();\"
onclick=\"document.loginfrm.user.value='username';
document.loginfrm.pass.value='password';
document.loginfrm.submit();\">". login ."</a>";
which should produce:
<a href="javascript:void();"
onclick="document.loginfrm.user.value='username';
document.loginfrm.pass.value='password';
document.loginfrm.submit();">login
</a>
As you have it now, you're closing the onclick attribute when you hit the quote at the start of the "username" value, which means the browser is interpreting username as another attribute and it just gets more confused from there...
Edit: sorry, fixed the html, rather than the php code...
You should do something like this..
<a href="javascript:void();"
onclick="document.loginfrm.user.value='username';
document.loginfrm.pass.value='password';
document.loginfrm.submit();">login
</a>
and with php it should be
echo '<a href="javascript:void();"
onclick="document.loginfrm.user.value=\"username\";
document.loginfrm.pass.value=\"password\";
document.loginfrm.submit();">
login
</a>';

Categories