Echo php string into onclick as arg - php

I have an html onclick that calls a javascript function below:
onclick="addInventory(<?php echo $product['id']?>)"
Once I add a second arg which is a string, the function breaks, I believe
I have put it in quotes but I'm not sure how.
Breaks using:
onclick="addInventory(<?php echo $product['id']?>,<?php echo $product['name']?>)"

PHP's json_encode, when used on a variable, will properly escape it for JS usage.
onclick="addInventory(<?php echo json_encode($product['id'])?>,<?php echo json_encode($product['name'])?>)"
For example:
>>> json_encode('This is "my string" and it has some \'nasty\' characters in it!');
=> "This is \"my string\" and it has some 'nasty' characters in it!"

Related

Using JS function with parameters in php

The JS function is
function func(arg){
alert(arg);
}
When I do
echo "<div onclick=\"func($arg)\">Text</div>";
in php, it doesnt work
but when I do
echo "<div onclick=\"func()\">Text</div>";
it works and an alert with undefined text pops up.
How do I pass argument?
You need to quote the arguments. e.g.
<?php
$foo = 'bar';
?>
echo "function($foo) { ... }";
is going to produce the code
function(bar) { ... }
where bar will be interpreted as an undefined variable.
Safest method is to output your PHP variables via json_encode(), to guarantee you're producing syntactically valid javascript. e.g.
echo 'function(' . json_encode($foo) . ') { ... }';
which would produce (in this case)
function ('bar') { ... }
You need to wrap $arg in quotes. Example:
echo "<div onclick=\"func('$arg')\">Text</div>";
(using single quotes around arg as you're using double quotes for the string)
You can do like this (if $args exists of course)
echo '<div onclick="func('.$arg.')">Text</div>';

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.

How to escape Javascript code that is echoed in PHP

I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';

What's the solution for this kind of problem?

<a onclick="run('Hi, Tim! I&#039;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>

Categories