unterminated string literal in javascript - 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)"

Related

Escape character removed when using selenium execute_script through python

I need to have these characters in my string: "'\;
userID = "__\"__\'__\;__"
I am running javascript through python to update the username field:
driver.execute_script("window.document.getElementById('username').value = '%s';" %userID)
Now my problem is that in the end my script becomes:
window.document.getElementById('username').value = '__"__'__\;__';
And this causes errors since I have single quote without escape character. How can I keep the escape character in front of the single quote?
Don't use interpolation. Instead, pass the value as a parameter to execute_script:
driver.execute_script("window.document.getElementById('username').value = arguments[0];",
userID)
The arguments you pass to execute_script after the script are available as arguments[0], arguments[1], etc. on the JavaScript side. (This is not a special Selenium thing but how JavaScript works. The script you give to execute_script is wrapped in a function object and function parameters are available on the arguments object.)
When you pass the value as a parameter like above, Selenium will serialize the Python value to its corresponding JavaScript value on the browser side and it will preserve your string.

Error Parsing JSON with escaped quotes

I am getting the following json object when I call the URL from Browser which I expect no data in it.
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
However, when I tried to call it in javascript it gives me error Parsing Json message
dspservice.callService(URL, "GET", "", function (data) {
var dataList = JSON.parse(data);
)};
This code was working before I have no idea why all of a sudden stopped working and throwing me error.
You say the server is returning the JSON (omitting the enclosing quotes):
{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}
This is invalid JSON. The quote marks in JSON surrounding strings and property names should not be preceded by a backslash. The backslash in JSON is strictly for inserting double quote marks inside a string. (It can also be used to escape other characters inside strings, but that is not relevant here.)
Correct JSON would be:
{"data":[], "SkipToken":"", "top":""}
If your server returned this, it would parse correctly.
The confusion here, and the reports by other posters that it seems like your string should work, lies in the fact that in a simple-minded test, where I type this string into the console:
var x = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
the JavaScript string literal escaping mechanism, which is entirely distinct from the use of escapes in JSON, results in a string with the value
{"data":[], "SkipToken":"", "top":""}
which of course JSON.parse can handle just fine. But Javascript string escaping applies to string literals in source code, not to things coming down from the server.
To fix the server's incorrectly-escaped JSON, you have two possibilities. One is to tell the server guys they don't need to (and must not) put backslashes before quote marks (except for quote marks inside strings). Then everything will work.
The other approach is to undo the escaping yourself before handing it off to JSON.parse. A first cut at this would be a simple regexp such as
data.replace(/\\"/g, '"')
as in
var dataList = JSON.parse(data.replace(/\\"/g, '"')
It might need additional tweaking depending on how the server guys are escaping quotes inside strings; are they sending \"\\"\", or possibly \"\\\"\"?
I cannot explain why this code that was working suddenly stopped working. My best guess is a change on the server side that started escaping the double quotes.
Since there is nothing wrong with the JSON string you gave us, the only other explanation is that the data being passed to your function is something other than what you listed.
To test this hypothesis, run the following code:
dspservice.callService(URL, "GET", "", handler(data));
function handler(data) {
var goodData = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
alert(goodData); // display the correct JSON string
var goodDataList = JSON.parse(goodData); // parse good string (should work)
alert(data); // display string in question
var dataList = JSON.parse(data); // try to parse it (should fail)
}
If the goodData JSON string can be parsed with no issues, and data appears to be incorrectly-formatted, then you have the answer to your question.
Place a breakpoint on the first line of the handler function, where goodData is defined. Then step through the code. From what you told me in your comments, it is still crashing during a JSON parse, but I'm willing to wager that it is failing on the second parse and not the first.
Did you mean that your JSON is like this?
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
Then data in your callback would be like this:
'"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"'
Because data is the fetched text content string.
You don't have to add extra quotes in your JSON:
{"data":[], "SkipToken":"", "top":""}

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")

Passing strings with Single Qoute from MVC Razor to JavaScript

This seems so simple it's embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct way to do it? And more importantly, where and how do you apply the proper string replacement code to prevent a single quote from becoming &#39 as in the resultant alert below?
Adding this into a single script block:
alert('#ViewBag.str') // "Hi, how's it going?"
Results in the following alert:
Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use
alert('#Html.Raw(ViewBag.str)');
However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have
ViewBag.str = "Hi, how\\'s it going?";
Another solution to use JSON string:
C#
ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";
Javascript
var j = #Html.Raw(ViewBag.str);
alert (j[0].Text);

JSON String as Javascript function argument

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)

Categories

Resources