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.
Related
I am trying to pass a variable from one page to another by appending it to the URL like this-
<a href='single.php?name=".$m['Title']." ' class='movie-beta__link'>
and in the next page(single.php), I am getting the url as-
$title= $_GET['name'];
echo $title;
But nothing is displayed and my URL looks like this-
http://localhost/mdb/single.php?name=
Can someone please point out if I am missing something here.
Try this
<a href='single.php?name=<?php echo $m['Title']; ?>' class='movie-beta__link'>Title</a>
You're getting your single and double quotes mixed up. With single quotes you have to append variables and with double quotes you can put them inside. But when you're outside of <?php tags you can use <?= to echo a variable.
<a href="single.php?name=<?= $m['Title'] ?>" class="movie-beta__line">
This will work above:
<a href='single.php?name=<?php echo $m['Title']; ?>' class='movie-beta__link'>Title</a>
if all this is in php echo, use <a href='single.php?name='".$m['Title']."' class='movie-beta__link'>Title</a>
And its good to avoid underscores on you class names
I have a PHP script that generates some Javascript for me in a manner like this:
foreach ($array as $element)
{
echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1].')">'.$element[2].'</a>';
}
My problem is that how can I escape so that the Javascript bit will look more like
<a onClick='MyFunctionTakesPHPValues("'.$element[0].','.$element[1].'")>'.$element[2].'</a>';
I hope this makes sense. The short version is that I feel i need triple quotes inside double quotes inside single quotes, but there is no such thing as triple quotes, but I believe there is some way to escape quotes to nest it up three times.
Same as always: encode as JSON.
echo '<a onClick="myFunctionTakesPHPValues('.json_encode($element[0]).','.json_encode($element[1]).')">'.$element[2].'</a>';
Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
Every value have to be escaped properly, as explained in this article
So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.
For the last element only HTML encoding is required.
foreach ($array as $element)
{
$param1 = htmlspecialchars(json_encode($element[0])); // better give them
$param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
$param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
<?=$param3?>
</a>
<? }
And yes, using raw JS in HTML attributes considered as a bad practice.
Use Like
echo "<a onClick='myFunctionTakesPHPValues(\"".$element[0]."\",\"".$element[1]."\")'>".$element[2]."</a>";
Use this:
echo "<a onClick='MyFunctionTakesPHPValues(\"'".$element[0]."','".$element[1]."'\")>'".$element[2]."'</a>'";
foreach ($array as $element)
{?>
<a onClick="myFunctionTakesPHPValues("<?php echo $element[0].','.$element[1].')>'.$element[2].'</a>'
}
?>
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];
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
<a onclick="run('Hi, Tim! I've got two', '">test</a>
The onclick event is not run at all.
The above is generated by something like this:
<a onclick="run(<?php echo htmlentities($str) ?>)">test</a>
How to fix it?
You are outputting the content of a string without quoting it
Put the echo statements in ''
<a onclick="run('<?php echo htmlentities($str) ?>')">test</a>
By the way, ' = '
$str, before being entity-encoded, is:
'Hi, Tim! I've got two', '
which is clearly not a valid JavaScript string literal. The apostrophe is HTML-encoded, which it shouldn't be yet, and there's some trailing nonsense.
You should create JavaScript string (and other) literals using the json_encode function. If you have $rawstr as:
Hi, Tim! I've got two
then json_encode will give you the correct JavaScript string:
'Hi, Tim! I\'ve got two'
so you can insert it into an HTML event handler attribute:
<a onclick="run(<?php echo htmlspecialchars(json_encode($rawstr)) ?>); return false;">test</a>
Note htmlspecialchars(), which is preferable to htmlentities(), as the latter will usually-needlessly HTML-escape all non-ASCII characters, which will mess them up if you don't specify the correct charset.
From PHP 5.3, you can use the JSON_HEX_ flags to ensure that the HTML-special characters are never in the output from json_encode, which saves you an encoding step:
<a onclick="run(<?php echo json_encode($rawstr, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT) ?>); return false;">test</a>
To make your life easier, encapsulate these common output-with-escaping methods into more simply-named functions:
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
function j($s) {
echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
}
function u($s) {
echo urlencode($s);
}
<a onclick="run(<?php j($rawstr); ?>); return false;">test</a>
And even better, avoid using inline event handler attributes at all by binding from script:
<a id="test">test</a>
...
<script type="text/javascript">
document.getElementById('test').onclick= function() {
run(<?php j($rawstr); ?>);
return false;
};
</script>