<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>
Related
Am I doing this correctly? As I understand it, if I define the "return" value as true when I call print_r, it should return a string. I have the following function:
function alert($string) {
echo '<script>alert("' . $string . '");</script>';
}
And when I pass that function a regular old quote-encapsed string, it works just fine and dandy, but when I feed it this:
alert(print_r($array,true));
Nothing happens and I don't see an error, yet echoing print_r($array,true) works. Thanks for any help you can offer, I'm just trying to understand what's going wrong here even though it is obviously a very minor problem.
Use
<script>
alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>
instead. Note the use of json_encode - this is to prevent any ' or other JS-metacharacters from introducing a JS syntax error, e.g.:
<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>
<script>
alert('<?php echo $name ?>');
</script>
would give you:
alert('Miles O'Brien');
^-- start of string
^--end of string
^^^^-- unknown variable/function.
Your alert function has two problems handaling that input.
first, as metioned, your JS is missing qutes.
Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:
alert("hello
world");
is invalid syntax.
so, this alert function will probably work:
function alert($string) {
$string=preg_replace('/\n/m','\\n',$string);
echo '<script>alert("' . $string . '");</script>';
}
print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.
Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.
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.
lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
xxxi have the_title() that returns some text, in this case Blue & Whiny
the problem as we can see is that the & character looks different
how do i turn Blue & Whiny into Blue & Whiny i tryed: htmlspecialchars_decode(the_title()), html_entity_decode(the_title()),htmlspecialchars(the_title()) and nothing.
i want to convert & to &
there is not much code to share, I just do this: <?php the_title() ?> and i get Blue & Whiny. If i use get_the_title() it wont display anything
Any ideas?
Thanks
edit1. ill share some code:
<script type="text/javascript">
function showShareUI() {
var act = new gigya.services.socialize.UserAction();
act.setUserMessage("Check out this article.");
act.setTitle("Trends on Explore Talent - <?php the_title(); ?>");
act.setDescription("<?php get_the_content(); ?>");
act.setLinkBack("<?php the_permalink(); ?>");
act.addActionLink("Check out this article", "<?php the_permalink(); ?>");
var image = {
src: 'http://xxx.com/wp-content/uploads/2011/05/BOTTOM_BANNER.jpg',
href: '<?php the_permalink();?>',
type: 'image'
}
act.addMediaItem(image);
var params =
{
userAction: act, // The UserAction object enfolding the newsfeed data.
onError: onError, // onError method will be summoned if an error occurs.
onSendDone: onSendDone // onError method will be summoned after
,showEmailButton: true
// Gigya finishes the publishing process.
};
gigya.services.socialize.showShareUI(conf, params);
}
function onError(event) {
alert('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
}
function onSendDone(event)
{
document.getElementById('status').style.color = "green";
document.getElementById('status').innerHTML = 'The newsfeed has been posted to: ' + event.providers;
}
</script>
I've tried everything. This starts to annoy me...
html_entity_decode() is the correct way to do it.
html_entity_decode("Blue & Whiny");
Will produce:
Blue & Whiny
If it's not working, make sure you don't have another issue - such as passing a string to it that is double encoded, or running htmlentities() on the string again later.
Demo: http://codepad.org/BHXGWXJi
Double check with a literal string and var_dump() the output, you should see the decoded version. Then var_dump(the_title()), to make sure you are actually passing what you think you are to html_entity_decode().
html_entity_decode should do the trick. If not, try to specify the third parameter $charset.
Something like:
echo html_entity_decode(the_title(), ENT_QUOTES, 'UTF-8');
the_title() directly prints the title, so adding html_entity_decode() directly around that won't work. You can, however, stop it from printing with its third function argument. E.g.
<?php echo html_entity_decode(the_title('', '', false)) ?>
There's also get_the_title(), which doesn't directly print the title, but it requires the ID of the post you want the title of, in contrast with the_title, which prints the title of the current post in The Loop. So you need to do something like this:
<?php echo html_entity_decode(get_the_title($post->ID)) ?>
And actually, you should be able to simply do:
<?php echo $post->post_title ?>
The only reason these utility functions are there is to escape things for you and add tags and stuff. If you just want the raw input, you can print it directly.
This won't fix all of your issues, though, because you're echoing it inside a JavaScript string, so you need to escape certain characters. json_encode() should do the trick, but see the question "Pass a PHP string to a Javascript variable (including escaping newlines)" for more details.
Try this:
echo(mb_convert_encoding(the_title(), "UTF-8", "HTML-ENTITIES"));
see if this works for ya
$convmap = array (0x0, 0xffff, 0, 0xffff);
//$str = mb_decode_numericentity (the_title(), $convmap, 'UTF-8' );
$str = mb_decode_numericentity ("&", $convmap, 'UTF-8' );
echo $str;
http://www.php.net/manual/en/function.mb-decode-numericentity.php
I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.
It works fine when it is not being echo'd.
echo('
<script type="text/javascript">
$(document).ready(function() {
$(\'input\').animate({backgroundColor:\"#F00\"},200);
});
</script>
');
any ideas?
I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.
You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:
echo('
<script type="text/javascript">
$(document).ready(function() {
$("input").animate({backgroundColor: "#F00"}, 200);
});
</script>
');
When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:
echo "<input type=\"text\" name=\"username\">";
as opposed to
echo '<input type="text" name="username">';
which makes your life a whole lot easier when you have to modify it.
Hope this helps !
You shouldn't use \" there, just "
Furthermore: a hex-color-value is no numeric value you can use for animate() .
By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.
i didnt test it, but try that:
$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo ' $(document).ready(function() {'.$nl;
echo ' $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo ' });'.$nl;
echo '</script>'.$nl;
the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).