echo a javascript function with parameters in php - php

I am trying to pass a JavaScript function with an onclick event in php. The problem I am facing is that the function that I need to pass has a parameter that needs to be in double quotes as follows:
onclick="removeElement("div8")"
Now when I use JavaScript to generate the parameter it comes out fine, but whenever I use an echo function in php, the following happens when I look at the function in the browser
onclick="removeElement(" div8")"
the code I am using to generate this is:
echo '<div><img src="img.png" alt="image" onclick="removeElement("div'.$x.'")" /></div>';
where $x is the number to be added to the parameter.
Is there a way that the function is returned as a whole and not get the space in between?

This is happening because you have quotes inside quotes. This will not work, and breaks the HTML parser. It is seeing the onclick as removeElement(, and then it sees an attribute called div8")".
Try this:
echo '.....onclick="removeElement("div'.$x.'")"...';
HTML entities are parsed inside attributes, so the result will be your working code.

Change your echo to this:
echo '<div><img src="img.png" alt="image" onclick="removeElement(\'div'.$x.'\')" /></div>';

You must escape quotes in javascript. Instead of
onclick="removeElement("div8")"
you should write
onclick="removeElement("div8")"

try escaping your single-quotes
echo '<div><img src="img.png" alt="image" onclick="removeElement(\'div'.$x.'\')" /></div>';

As long as you do not use any spaces in the attribute value you can ommit the quotes around the html attribute values. All browsers will handle that fine. So you can write:
onclick=removeElement("div8")
You could also use the single quotes:
onclick="removeElement('div8')" or
onclick='removeElement("div8")'
Or you can escape the double quote:
echo '<div><img src="img.png" alt="image" onclick="removeElement(\"div'.$x.'\")" /></div>';

But a simpler solution would be to write in html directly:
?>
<div>
<img src='img.png' alt='image' onclick='removeElement("div<?php echo $x; ?>")' />
</div>

when you using php echo try this code
<a href="javascript:add_cota(<?php echo $value->ID .','.$k.', \''.$st.'\'';?>)">
$st
is the string param to avoid the ReferenceError: Active is not defined error

Related

Included php tag in html attribute

How do I include a php tag in an HTML attribute? I still find it quite tricky.
This is the HTML attribute:
src="https://customer.site.com/?language=en_US&portal=Default"
The thing is, ?language should accept a dynamic value. That value is stored in $lingos[$wmpl_langcode].
So I've been trying many variations and I'm still stuck.
I've got this now but it doesn't seem right.
src=<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
I don't want to waste any more time on it. Any tips would be great.
you was just missing one double quote and the ; at the end of the echo to end the instruction:
src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode]; ?>&portal=Default"
You are now missing quotes for the attribute.
This however would be perfectly fine:
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
If you like it a bit more clean without confusing quotes:
<img src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode] ?>&portal=Default"/>
You should also think about urlencode():
<img src="https://customer.site.com/?language=<?php echo urlencode($lingos[$wmpl_langcode]) ?>&portal=Default"/>
To make it "more clean", you should use a templating engine.
When you directly use echo to print the dynamic link, the quotes are not present there.
Try this:
src="https://customer.site.com/?language=<?=$lingos[$wmpl_langcode] ?>&portal=Default"
OR
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"

Echo a html phrase, with onclick function

Hello dear programmers,
I have a problem with the echoing of a html phrase with an onclick function that executes a javascript function. I want to build a tabpage, for a image gallery.
The echo:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".$album."')'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
Everything goes well, except the passing of the variable in the onclick function, as you can see here. What actually the HTML looks like:
<a class="tablinks" onclick="openAlbum(event, " aubing')'=""><h1 class="galleryheader">Aubing</h1></a>
But this onclick event has to look like this:
onclick="openAlbum(event, 'Aubing')"
Is there a way to actually realise this or do I have to find an other option?
I actually tried switching " with ', didnt go very well....
Thank you for everybody that tries to help
Try this:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, \"$album\")'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
see escaped double quotes in the onclick definition
addslashes is what you are looking exactly.And also you have to remove the single quotes in variable.Try to do the following way.
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".addslashes($album)."')'><h1 class='galleryheader'>".$album."</h1></a><div id=".addslashes($album)." class='tabcontent'>";
Hope this help.
An alternative:
$escapedString = htmlspecialchars('This is a test string: < > & \' " end.', ENT_COMPAT);
echo "<div onclick='alert(this.dataset.name)' data-name=\"$escapedString\">Click Me</div>";
This approach avoid quotes inside function, no quotes nesting.

onclick function using php

My onclick function is not working.It is not passing the value (parameter)?
<img class="img-thumbnail thumbnails" src="download.jpg" alt="bridget_moynahan_00.jpg" title="bridget_moynahan_00.jpg" onclick="showImage(<?php echo "download.jpg";?>);" />
Your code is producing the following JavaScript:
showImage(download.jpg);
In JavaScript, as in other languages, string literals need to be surrounded by quotes. For example:
showImage('download.jpg');
One way to do that here would be like this:
showImage('<?php echo "download.jpg";?>');
Or possibly:
showImage(<?php echo "'download.jpg'";?>);
Try like this
onclick="showImage('<?php echo "download.jpg"; ?>')";
Try this:
onclick="showImage(<?php echo "'download.jpg'";?>);"
Also make sure that you have define the function showImage or that you have add the script file like:
<script src="/js/custom_filename.js"></script>

Single quote within single quotes PHP

I have a HTML achor tag like below:
echo '<a href="javascript:tempBuy('.$res_get_price[0][0].','.$res_get_price[0][1].','.$res_get_price[0][2].','.$dt_str.')">'.$res_get_price[0][0];
And the corresponding javascript function tempBuy() is
function tempBuy(rate,veg_name,market_name,dt)
{
alert(dt);
}
But the problem is it does not alert at all ! May be I need to include the variable names within single quotes in tempBuy() function. I tried tempBuy(\'var1'\,\'var2\'...) but it shows error. How can I able to to that. Thanks .
Source for the part shows like this:
<td width="120px" class="">56.0
</td>
<script>
function tempBuy(rate,veg_name,market_name,dt)
{
alert(rate);
}
</script>
You didn't wrap your javascript arguments in quotes. You need to wrap each variable in single quotes, since you used double quotes for "href" attribute. Another thing is that you didn't close up "a" HTML tag.
echo ''.$res_get_price[0][0].'';
If there is anything in your variables that is not a valid javascript literal you have to make it a string like:
echo '<a href="javascript:tempBuy(\''.$res_get_price[0][0].'\' ...
If there are ' in your variables you have to replace them with \' as well.
As you can see form the rendered output, you need to quote the last 3 arguments which are non-numeric. The correct output should be: javascript:tempBuy(56.0,'Apple','Bangalore','2013-05-18')
The corrected PHP code is:
echo ''.$res_get_price[0][0].'';`
echo "<a href=\"javascript:tempBuy('".$res_get_price[0][0]."','".$res_get_price[0][1]."','".$res_get_price[0][2]."','".$dt_str."')\">".$res_get_price[0][0];

jQuery string is not defined

I'm sending data to function by onclick event but I can't get string value I just getting integer value, it say that 'value' is not defined. what is the problem.
My code is:
<a href="javascript:void(0)"
onclick="begin(<?php echo $data['user_id'];?>,
<?php echo $data['name'];?>);">
This is my function:
function begin(id,name)
{
alert(id);
alert(name);
}
I'm not getting name value, if I pass hard-code string then its also not getting here only integer are accessible.
You need to wrap your parameters in quotes to make it a string.
<a href="javascript:void(0)" onclick="begin('<?php echo $data['user_id'];?>','<?php echo $data['name'];?>');">
As Matt says, without quotes it won't be recognised.
That said, I don't think his answer is correct. I would prefer this code: (whitespace added for legibility)
<a href="javascript:void(0);" onclick="begin(
<?php echo htmlspecialchars(json_encode($data['user_id'])); ?>,
<?php echo htmlspecialchars(json_encode($data['name'])); ?>
);">
json_encode (docs) is good for passing any PHP variable (except Resources) into JavaScript. In this case, it will add quotes around the string, and escape characters as needed with backslashes. Since it's going in an attribute, you need htmlspecialchars to convert symbols to be safely insertable.

Categories