Call a javascript function with json_encode parameter - php

I would like to call a function onclick, but with a json_encode parameter like this:
<a href="#" onclick="javascript:table1Modif(<?php echo substr(json_encode($res['base']),1,-1); ?>);return false;">
And the Jquery function just alert the parameter:
<script>
function table1Modif(key){
$('#table1').html(function() {
alert(key);
});
}
</script>
But I have an "undefined" error!
I am sure that it's due to json_encode, but I don't know how to solve it.
Thank you!

It looks like you are passing a string to json_encode in order to generate a JavaScript string literal (which is not valid JSON).
You are using substr to remove the quotes from this string.
JavaScript will therefore see an identifier (which in that context will be treated as a variable).
You need a string literal, so the first thing to do is remove the substr call.
This will create a new problem. You are inserting the string into an HTML document, but not expressing it as HTML. The " character at the start of the string literal will therefore be treated as end of attribute value, which you don't want.
When inserting non-HTML content into an HTML document you need to express it as HTML. Run the code through the htmlspecialchars function to do this.
onclick="table1Modif(<?php
echo htmlspecialchars(
json_encode($res['base'])
);
?>);return false;"
Incidently, I've removed the entirely useless javascript: label. You don't have a loop to break or continue from so it isn't doing anything. While you're at it, you should replace href="#" with something more sensible. Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.

Related

Pass string from PHP to onclick handler of anchor tag

I am trying to pass a value on the server side to the onclick handler of a tag, but it is giving different result on the client side when I click on the link.
My PHP code:
$any="link1";
echo(" <a id='link1' href='#' onclick='VisibleFalse($any)'>[+]</a><span><b>$candidatename</b></span>");
I want to pass the string "link1" to the function VisibleFalse, which is showing the string as an alert:
function VisibleFalse(ID)
{
alert(ID);
}
But it is printing "http://localhost/..." in the alert.
I would appreciate any of your suggestions.
Problem is, you're passing a string and you forgot to add quotes to it so that the end result would be a string inside that JavaScript function. Here's a better way to look at this:
$any="link1";
// First, echo isn't a function. It can be faked to be used as one, but that's not recommended
// Second, sort out your quoting like this:
echo '<a id="link1" href="#" onclick="VisibleFalse(\''.$any.'\')">[+]</a><span><b>'.$candidatename.'</b></span>';
// OR
echo "<a id='link1' href='#' onclick='VisibleFalse(\"$any\")'>[+]</a><span><b>$candidatename</b></span>";
String literals in JavaScript must be quoted.
onclick='VisibleFalse("$any")'>
(But intrinsic event attributes considered to be more pain then they are worth, as is Javascript embedded in HTML embedded in PHP. Use unobtrusive JavaScript instead.)
You also need to make sure that $any does not include any quote characters that would terminate the string literal (and you should probably be making it HTML safe with htmlspecialchars so it doesn't terminate the attribute value)
Use the HTML Unicode (other characters can be found here) equivalent to quotations '.
echo(" <a id='link1' href='#' onclick='javascript:VisibleFalse('$any')'>[+]</a><span><b>$candidatename</b></span>");

Passing special characters from php to javascript

I am passing a string variable from php to javascript.
The string contains "
But javascript doesn't get it.
How can I escape this character?
UPD:
To be more clear, first I don't want to make many changes in the code (not written by me)...
The string is passed this way:
var string = '<? echo $string;?>' ;
Single quotes are used. Maybe there is a way to change smth. in the string itself?
You could use the json_encode method:
<script type="text/javascript">
var value = <?php echo json_encode($someValue); ?>;
alert(value);
</script>
Assuming a string delimited using double quotes, add_slashes will do the job in the particular case.
Wrapping the data in an associative array, running it through json_encode and altering the JS to expect the changed data structure is a safer approach though (since that will take care of other characters which are significant, such as literal new lines).
(Technically speaking, with the current implementation of json_encode you could skip wrapping it in an associative array … but a plain string isn't valid JSON and I'm inclined to avoid depending on a function that is supposed to generate JSON not throwing an exception when given a data structure that can't be turned into JSON).
If you are embedding the script in an HTML document you will also have to take steps to ensure that the resulting JS doesn't contain any HTML that could cause issues (such as " in an script included as an attribute value).
Use urlencode() function in php code to pass the string to javascript code and decodeuri() in javascript to decode that string.

javascript quotes inside quotes, string literal issue

I am trying to display text in a javascript tooltip
I keep getting unterminated string literals even though:
a) the quotes are being slashed, b) there are no line breaks
The text I am trying to display is:
"No, we can't. This is going to be terrible."
(its a quotation from an individual and I want those quotes to display in the tooltip)
My tooltip function works like this
onMouseOver="Tip('string here')"
After I run the string through my function to clean for javascript
function jschars($str) {
echo preg_replace("/\r?\n/", "\\n", addslashes($str));
}
It comes out looking like this in HTML:
onMouseOver="Tip('\"No, we can\'t. This is going to be terrible.\"')"
This gives me the error unterminated string literal for the first \ in Tip('\
I'm guessing its because im trying to put quotes directly inside the single quotes, how can I get around this for situations like this? (I have tried htmlspecial chars, such as replacing the " with & quot ; - I still get the error
It's because you're putting double-quotes inside the value of an XML (or html) element:
<div onMouseOver="Tip('\".......
the back-slash doesn't escape it from the context of xml/html. Technically, you'll need to entity-encode the string (after you javascript-escape it). Something like this:
<div onMouseOver="Tip('\"No, we can\'t. This is going to be terrible.\"')" >
Various browsers may or may not deal with that properly. A much better way to approach it would be to give the element an id (or a class, or some other way for you to select it), then add the mouse over handler from a standalone script.
Because of the structure of what you're doing:
onMouseOver="Tip('string here')"
...you have to do two things:
As Lekensteyn said, you need to use htmlspecialchars to turn any special HTML characters into character escapes. It does things like turn " into ", which means you can safely enclose the attribute in " characters.
But you're not just using this as an attribute, you're also putting it inside a string literal, which means you also need to do JavaScript escaping on the string. Otherwise, (in your case) a single ' character or backslash will mess up the string. So your jschars function also needs to (in order) A) Convert \ to \\, B) Convert ' to \'. That's the minimum, anyway, really you need a thorough "make this safe to put inside a JavaScript literal" function. From your question, I sort of had the impression you were doing this manually, but better to automate it for consistency.
Off-topic: Separately, I would recommend moving away from using attributes to attach handlers. Instead, look into attachEvent (IE) and addEventListener (W3C), or better yet look at a library like jQuery, Closure, Prototype, YUI, or any of several others that will smooth things out for you. For instance, attaching a mouseover handler to:
You can use this handler to handle the mouseover:
function handler() {
Tip('Your message here');
}
...which you then hook up like this with raw DOM stuff (obviously you'd make a utility function for this):
var div = document.getElementById('foo');
if (div.attachEvent) {
// Uses "onmouseover", not "mouseover"
div.attachEvent('onmouseover', handler);
}
else if (div.addEventListener) {
// Uses "mouseover", not "onmouseover"
div.attachEvent('mouseover', handler, false);
}
else {
// Fallback to old DOM0 stuff
div.onmouseover = handler;
}
Here's how Prototype simplifies that hook-up process:
$('foo').observe('mouseover', handler);
Here's how jQuery does:
$('#foo').mouseover(handler);
You should use htmlspecialchars() for this purpose. The problem is ", but HTML won't understand javascript quoting, so it stops at \".
function jschars($str) {
echo htmlspecialchars(preg_replace("/\r?\n/", "\\n", $str), ENT_QUOTES);
}
You could keep the string in javascript instead of HTML. eg:
<a onmouseover="Tip(this, 123)">choice</a>
Then something like:
var texts = {
123:"No, we can't. This is going to be terrible.",
...
};
function Tip(elm, txtId){
showTip(elm, texts[txtid];
}

Escape brackets on php for javascript

For example i've a php script with this content:
<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?>
But the alert get broken by the last "(". How can i solve this?
You should enclose alert parameter with quotes:
echo "<script>alert('$msg'); return false;</script>";
What your code outputs to the browser was:
<script>alert(The what happened >:(); return false;</script>
which is not a valid javascript, after putting the quotes, it becomes:
<script>alert('The what happened >:('); return false;</script>
which is valid javascript.
You need to put it in a JavaScript string, otherwise it gets interpreted like this, which is meaningless and causes an error:
<script>alert(The what happened >:(); return false;</script>
Notice the single quotes in the alert() call which denote a JavaScript string (double quotes work too):
<?php
$msg = "The what happened >:(";
echo "<script>alert('$msg'); return false;</script>";
?>
It is also a good idea to escape the content inside to mitigate XSS, using htmlspecialchars().
The other answers are along the right lines, but it is not sufficient to just put quotes around the string, if it can be any arbitrary string. If the string itself contains a quote, backslash, or newline, that will break the JavaScript string literal. If the string contains </script (or just </ in some cases) that will break the <script> block. In either case, if user-supplied input is involved, that gives you a big old cross-site-scripting security hole.
Whilst you may not need it for this specific value of $msg, it's a good idea to get used to JS-string-literal-escaping any text you output into a JS string. Whilst you can do this manually by adding backslashes, it's generally much easier to just use the built-in JSON encoder, which will work for other types like arrays and objects as well as strings.
<script type="text/javascript">
alert(<?php echo json_encode($msg); ?>);
return false; // huh? return, in a <script> block??
</script>
alert() accepts a string argument; you must enclose the text you're passing to it in quotes (either single or double) and insure that any matching quotes within the string are escaped by backslashes.
In your case single quotes would suffice:
echo "<script>alert('$msg'); return false;</script>";
Depending on the context, you might also just do:
<?php
$msg = "The what happened >:(";
?>
<script>alert("<?php echo $msg ?>"); return false;</script>
If there is no need to echo HTML or JavaScript code, then don't do it. It is easier to maintain .

How to show html tags converted by PHP's htmlentities into div using jQuery?

I have a dynamic string from PHP that I encoded using htmlentities() so I can pass it on AJAX using jQuery and JSON. Now I got something like
{ "error": "false", "html": "<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>" }
and when I want to show it in an AJAX success callback function like:
success: function(json) {
if(json.error == 'false')
$("#users_container").html(json.html);
else
showMsg(json.msg);
}
what's displayed in the is the entities itself
<div id="user_add_title">Adding New User<div class="showhide-div"><a class="hideShowToggle" href="#" onclick="$('#account_title').show();$('#account').show();$('#users_container').html('')">[cancel]</a></div></div>
instead of being rendered by the browser.
If I use html or text as dataType in my jQuery AJAX call, the tags are rendered properly. I want to use JSON because I need to catch if the process has an error or not.
You don't need to encode your own markup with htmlentities when passing it to jQuery. Simply remove the call to htmlentites() and send your marked up HTML.
The exception is, if some part of the code contains text supplied from the user. In this case, you must htmlencode() that text, and leave it encoded even when it's appended to a DOM element for display.
I have solved it! Instead of using PHP's htmlentities() which converts greater than and less than signs as well as the quotes, I just used addslashes() to only convert (or add backslashes) characters that need backslashing such as the quotes.
I figured out that the quotes were the ones causing the json not being parsed correctly, the reason why I used htmlentities in the first place, thinking that converting everything would solve it. Thanks for your valuable input.

Categories