JSON String as Javascript function argument - javascript

I am trying to define a pure JSON string as an argument in a Javascript function.
Below is the way I want to define it:
Link
Firebug gives me an error alert: unterminated string literal, even when I escape the double-quotes on the JSON string.
How can I solve this?
Thanks.

Use " for your double quotes, then in js_func(), replace them with actual double quote characters (") before evaluating your JSON string. (thanks for the demo Matthew, I updated your fiddle with the example from the question:)
http://jsfiddle.net/brillyfresh/kdwRy/1/

simply defining the link as Link works fine. JSON is valid JavaScript, you don't need to enclose it in ''s.
I also suggest to use an EventListener (element.addEventListener()), this makes the html cleaner and would reduce this problem to nothing.

ryou are either trying to pass the parsed object or pass a string
Object: onclick="js_func(arg_1, arg_2, {'key': 'value'});"
String: on_click="js_func('arg_1', 'arg_2', '{\"key\": \"value\"}'); return false"
All I've got handy to test is firebug interpreter but both worked fine for me.
>>>>'{\"key\": \"value\"}'
"{"key": "value"}"
>>>> {'key': 'value'}
Object {key="value"}
(I don't mean to presume whether arg_1 and arg_2 are strings or variable names, and it doesnt matter. just did the same thing as with the JSON)

Related

Passing a string value from c# file to js file

I am trying to pass a string value from c# file to js file.
If I try to pass an int value, then I can pass it, but I am unable to pass string value.
string value = "abc";
int a=5;
TableCell.Attributes.Add("onclick", "F1("+value +")"); //NOTHING HAPPENS
TableCell.Attributes.Add("onclick", "F1("+a +")"); //Works Perfectly
js file
function F1(value) {
alert(value);
}
Pass string value in quotes ''
Use
TableCell.Attributes.Add("onclick", "F1('"+value +"')");
^ ^
Otherwise it treated as variable. Currently you must be getting error in browser console.
Consider what your HTML will look like.
First version:
onclick="F1(abc)"
Second version:
onclick="F1(5)"
Clearly the second version is passing the value 5. The first version is passing the value of abc - whatever that is, within the context of the Javascript you're executing.
You could quote the string, making sure that you escape quotes etc - I'm assuming that in reality, your value is fetched dynamically from somewhere, and you might not have much control over the content. Hopefully there's something within whatever ASP.NET version you're using that will let you do that, such as HttpUtility.JavaScriptStringEncode.
For example, to get the string abc in your call, you want the attribute to be:
onclick="F1('abc')"
but if to get the string I don't know in your call, you want the attribute to be:
onclick="F1('I don\'t know')"
The key is to look at the generated HTML - pretend you're the browser, and look at the world from its perspective. Once you've worked out what HTML you want to generate, writing the code to do so is often relatively simple.
Try adding single-quotes around the value when building it in your C# string. In your first scenario, the Js is receiving:
F1(abc);
Which it reads as being the variable abc. Try adding single quotes (and it's probably best to use string.format, BTW):
TableCell.Attributes.Add("onclick", string.Format("F1('{0}')", value));
When you use the string, it would produce the JavaScript code F1(abc). That would interpret abc as a variable name, not a string literal.
Add apostrophes around the string to make it a string literal:
TableCell.Attributes.Add("onclick", "F1('" + value + "')");
If the string can contain apostrophes or backslashes, you would need to escape them:
TableCell.Attributes.Add("onclick", "F1('" + value.Replace("\\", "\\\\").Replace("'", "\\'") + "')");
This will take care of escaping any special characters (i.e. quotes, etc...)
TableCell.Attributes.Add("onclick", "F1('"+HttpUtility.JavaScriptStringEncode(value)+"')");
If you're passing a string through the argument, you need either " or ' characters to delimit it. Your variable name is translating to (adb) in the call. ("adb") or ('adb') would be the string value.
That's because it will print
F1(abc)
So it will look for a variable called abc.
You should use
TableCell.Attributes.Add("onclick", "F1(\""+value +"\")");
So the output will be
F1("abc")

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.

unterminated string literal in javascript

I have one string in my JSON. the value is To be Reviewed.
I am retrieving this string in my client side using data[i].status syntax. It fetches the correct value but when I send this syntax as paramter it gives unterminated string literal error on client side.
My code is:
onClick=test('"+data[i].product+"','"+data[i].status+"').
How can I send the string value in another function?
thanks in advance.
As you are appending variables you do not need the quotes around them, only the value you are assigning to the onClick parameter. Assuming your test function accepts two parameters, this should work:
onClick="test(data[i].product, data[i].status)"

Escape quotes in Javascript/Chameleon template

I am trying to pass a python dictionary from a chameleon template to a javascript function. But since the dictionary contains single quotes or ' which need to be escaped I get an error in firebug that says : SyntaxError: missing ) after argument list.
My code looks like this:
<div id = "divsfp">
<input type="button" id="sfp" value="SFP"
onclick="get_sfp('${dict_value}')"></input></div>
Where dict_value is a python dictionary. How can I escpae ' in chameleon template before passing the data or in Javascript function itself?
You need to JSON encode the dictionary. You don't then need to put quotes around the dictionary, and JavaScript will see it as a JavaScript object.
Use double-quotes, encoded as &quot:
onclick="get_sfp("${dict_value}")"
Chameleon will escape any double-quotes in dict_value.
You can try this, if this helps
"get_sfp('"+${dict_value}+"')"
Also from your implementation it seems that the dict_value is the variable you already know. So whats the problem accessing it from the get_sfp function.
Sorry couldn't comment as I still don't have that privilege.

alerting double encoded character

I'm trying to alert document.cookie when the dot is double encoded, but it doesn't work.
here's my code:
<script>alert(unescape(document%252Ecookie))</script>
How can i make it work using double encoding on the dot?
Thanks.
No idea what you are trying to do really, but here are some clarifications:
unescape() works on strings. it takes a string and returns another string. document%252Ecookie is not a string, so you cannot use unescape() on it.
To use unescape, put quotes around "document%252Ecookie"
unescape(unescape("document%252Ecookie")) will give you the string "document.cookie" (remember, unescape goes from strings to strings). If you alert this you will have an alert box saying "document.cookie", which is probably not what you are looking for. To get the contents of document.cookie you can use eval(). It takes a string and evaluates the contents of it.
So to do what you want to do you would type:
alert(eval(unescape(unescape("document%252Ecookie"))))
No idea of why you would want to do this, but this is how it can be done. I want to point out that this code is pretty stupid, but hopefully I've made some things more clear to you.

Categories

Resources