javascript syntax for passing variables to function - javascript

I have a JavaScript hyperlink that is not passing variable to function, undoubtedly due to syntax. Can someone please spot error.
jsfiddle: http://jsfiddle.net/kSVVX/
js
function follow(id){
alert(id);
}
html
<a href='javascript:void(0);' onclick= 'follow('1');'><img src='images/test.gif' border=0 alt='follow'></a>
Note: The reason that I am using all apostrophes is that this link is actually getting echoed from php where a long string is enclosed in quote marks (as certain things in the string must be in apostrophes.) I have a feeling this is source of problem, but have not succeeded in solving it by changing punctuation around.
Thanks for any suggestions.

You are using ' characters to delimit your JavaScript string and the HTML attribute value it is embedded in.
This results in:
onclick= 'follow('
Either:
Avoid intrinsic event attributes (which you should be doing anyway, unobtrusive JavaScript is recommended).
Use different characters to delimit the attribute value (onclick="follow('1');") or string (onclick= 'follow("1");')
Use HTML entities to include the quote mark you are using in the data for the attribute value (onclick= 'follow('1');')

Related

Despite single quotes being encoded using htmlspecialchars, JavaScript is still complaining that these quotes need to be escaped in the function call

Something strange is occurring and I'm stumped.
I have a link that looks basically like this:
Link
As you can see, I'm calling function uploadVariantPicture with parameter "size:'test2&#039".
However, when I actually click the link, JavaScript complains that the two encoded single quotes aren't being escaped. I'm getting the following error:
SyntaxError: Unexpected identifier 'test2'. Expected ')' to end an argument list.
If I decode the two encoded single quotes and escape them using a backslash, then the function call succeeds. But the problem is I need it encoded. I cannot leave it unencoded and escape the quotes. This won't work for my situation.
Any help is greatly appreciated. I'm super confused.
HTML character entities and escapes are replaced by the HTML parser when parsing source. For quotation marks, it allows inclusion of the same kind of quotation mark in an HTML attribute that is being used to quote the attribute value in source.
E.G.
<element attribute=""">
<element attribute='''>
in source would produce attribute values of " (double quote) and ' (single quote) respectively, despite being the delimters used to quote the attribute value in HTML source.
Hence
Link
will produce an href attribute value of
javascript:uploadVariantPicture('size:'test'');
after removal of the outer double quotes by the HTML parser.
Options could include escaping double quotes (HTML ") inside the href value appropriately (it depends on the syntax accepted by uploadVariantPicture), including backslash escapes before the single quotes as mentioned in the post, or not using the javascript: pseudo protocol at all, in favor of adding an event listener in JavaScript.
Not using javascript: pseudo protocol is highly recommended - basically it's a hold over from HTML3.
Consider attaching an event handler properly using JavaScript instead so you don't have to worry about escaping issues, and so that you don't have to rely on the pollution of the global object for the script to work:
const uploadVariantPicture = (arg) => console.log(arg);
document.querySelector('a').addEventListener('click', () => {
uploadVariantPicture("size:'test2'");
});
<a>Link</a>
I can't think of any situations in which an inline handler would be preferable to addEventListener, unless you were deliberately trying to exploit an XSS vulnerability.

Javascript with Special Chartecter

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

Selecting element by unescaped data attribute

Without going into specifics why I'm doing this... (it should be encoded to begin with, but it's not for reasons outside my control)
Say I have a bit of HTML that looks like this
<tr data-path="files/kissjake's files"">...</tr> so the actual data-path is files/kissjake's files"
How do I go about selecting that <tr> by its data path?
The best I can currently do is when I bring the variables into JS and do any manipulation, I URLEncode it so that I'm always working with the encoded version. jQuery seems smart enough to determine the data-path properly so I'm not worried about that.
The problem is on one step of the code I need to read from a data-path of another location, and then compare them.
Actually selecting this <tr> is what's confusing me.
Here is my coffeescript
oldPriority = $("tr[data-path='#{path}']").attr('data-priority')
If I interpolate the URLEncoded version of the path, it doesn't find the TR. And I can't URLDecode it because then jQuery breaks as there are multiple ' and " conflicting in the path.
I need some way to select any <tr> that matches a particular data-attribute, even if its not encoded in the html to begin with
First, did you mean to have the extra " in there? You will have to escape that, as it's not valid HTML.
<tr data-path="files/kissjake's files"">...</tr>
To select it, you need to escape inside the selector. Here's an example of how that would look:
$("tr[data-path='files/kissjake\\'s files\"']")
Explanation:
\\' is used to escape the ' inside the CSS selector. Since ' is inside other single quotes, it must be escaped at the CSS level. The reason there are two slashes '\` is we must escape a slash so that it makes it into the selector string.
Simpler example: 'John\\'s' yields the string John\'s.
\" is used to escape the double quote which is contained inside the other double quotes. This one is being escaped on the JS level (not the CSS level), so only one slash is used because we don't need a slash to actually be inside the string contents.
Simpler example: 'Hello \"World\"' yields the string Hello "World".
Update
Since you don't have control over how the HTML is output, and you are doomed to deal with invalid HTML, that means the extra double quote should be ignored. So you can instead do:
$("tr[data-path='files/kissjake\\'s files']")
Just the \\' part to deal with the single quote. The extra double quote should be handled by the browser's lenient HTML parser.
Building off of #Nathan Wall's answer, this will select all <tr> tags with a data-path attribute on them.
$("tr[data-path]");

Using JavaScript single and double quotes for href's

I am having problem with escaping the single and double quotes inside the hrefs JavaScript function.
I have this JavaScript code inside href. It's like -
click this
Now, since double quotes inside double quote is not valid, I need to escape the inner double quotes for it to be treated as part of the string -
so, I need to do this -
click this
The problem is, even the above code is not working. The JavaScript code is getting truncated at -- myFunc(
I tried with the single quote variation too - but even that doesn't seem to work (meaning that if I have a single quote inside my string literal then the code gets truncated).
This is what I did with a single quote:
<a href = 'javascript:myFunc("fileDir/fileName.doc" , true)'> click this </a>
This works, but if I have a single quote inside the string then the code gets truncated in the same way as that of double quotes one.
Using backslashes to escape quotes is how it works in JavaScript, but you're not actually writing JavaScript code there: you're writing HTML. You can do it by using the HTML escaping method: character entities.
" // "
' // '
For example:
...
In case anyone needs to escape some thing like this:
<a href="www.google.com/search?q="how+to+escape+quotes+in+href""</a>
You can use ASCII code for double quotes %22:
<a href="www.google.com/search?q=%22how+to+escape+quotes+in+href%22"</a>
It is especially useful if you pass the link to JavaScript from PHP
As a general best practice, use double-quotes in HTML and single-quotes in JavaScript. That will solve most of your problems. If you need a single-quote in a JavaScript string, you can just escape it using \' - and you probably shouldn't be nesting literal strings any deeper than that.
As noted elsewhere, HTML entities are a possibility if the code is embedded in HTML. But you'll still have to deal with escaping quotes in strings in your JavaScript source files, so it's best to just have a consistent strategy for dealing with JavaScript.
If you are following this strategy and end up with a double-quote embedded in your JavaScript embedded in your HTML, just use the HTML entity ".
Normally, this kind of code is working without problems:
Click this
With this code, do you have any problem?

Categories

Resources