SyntaxError: identifier starts immediately after numeric literal in Firebug - javascript

I'm getting that error when I call this javascript function:
function kickUser(id_userChat){
$.post("chatFuncs.php", { action: "kick", id_user: id_userChat });
}
this "kickUser" function is generated for every user connected to my chat box, like this
$listUsers .= '<img src="imgUsers/'.$DBClass->nomImg($rowUsers['id_user'],$posImg).'" height="'.$heightImg.'" width="'.$widhImg.'"/>
<span class="styleMsg">'.$rowUser['nameUser'].'</span>
Kick</br>';
and the action "kick" is just an update to my database where I remove the user from my chatUsers table
If I change $rowUsers['id_user'] for $rowUsers['userName'] the error changes to:
ReferenceError: 'userName' is not defined (i changed the real name of the user for 'userName' just for this example).

Identifiers in JavaScript can't begin with a number; they must begin with a letter, $ or _.
I'm guessing it's coming from this:
onclick="kick_user('.$rowUsers['id_user'].')">Kick</a>
If you mean to pass a string, then you need to quote the value being passed.
onclick="kick_user(\"'.$rowUsers['id_user'].'\")">Kick</a>
I don't know PHP, so maybe you need different escaping, but this should give you the idea.

The resulting JavaScript code will be
kickUser(userName)
…and obviously there is no js variable userName. You want to pass a string instead:
kickUser('userName');
So add the quotes/apostrophes to the output, and don't forget to escape the $rowUsers['userName'] properly. It's quite the same for $rowUsers['id_user'], which seems to have output even an invalid identifier.

Related

Dialogflow system.entity location: location.admin-area is not defined in online editor

I use system entity #sys.location in an intent in a Dialogflow agent. In the fulfillment section, I have this function in online code editor:
function testLocation(agent) {
//check object location
console.log(' location is ' + JSON.stringify(agent.parameters.location));
if(agent.parameters.location.city) {
//do smthing
}
else if (agent.parameters.location.admin-area){
agent.add(`this is not recognized ` +agent.parameters.location.admin-area);
}else{
//....
}
}
Point is that I receive a warning sign in the editor saying 'area is not defined', but I can see its values from the Firebase Console :
{"country":"","city":"","admin-area":"Piemonte","business-name":"","street-address":"","zip-code":"","shortcut":"","island":"","subadmin-area":""}
Any clues?
Thanks in advance
You're tripping over a JavaScript syntax issue.
The expression
agent.parameters.location.admin-area
is being evaluated as
agent.parameters.location.admin - area
that is to say agent.parameters.location.admin minus area, which is causing an error because, as the error says, the "area" attribute of "location" isn't defined.
In this, agent.parameters.location is an Object, and JavaScript provides two ways to access attributes of an Object
You can use bracket notation [expression] where the expression inside the brackets should evaluate to the name of an attribute of the object. Usually this needs to be a string.
In some cases, you can use dot notation .name where the name is the name of the property. But this assumes the name doesn't have characters used by other JavaScript syntax.
Note the difference between "expression" and "name". The first lets you use a variable with a string in it, or something else you've computed. The second requires you to hardcode it.
In your case, you can use bracket notation to get the value you want. So something like
agent.parameters.location["admin-area"]
should work.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

Uncaught ReferenceError JavaScript

Ok, so I have a template which I am using to print a couple of users to a table.
function PrintUsers(item) {
$.template('userList', '<tr onClick="OnUserPressed(${Identifier})">\
<td>${Firstname}</td>\
<td>${Lastname}</td>\
</tr>');
$.tmpl('userList', item).appendTo("#UserTableContainer");
}
When I press a user I want his/hers unique identifier to be passed to a function called OnUserPressed which I am declaring in the template. The code below is just a test to see if it actually passes the data to the function.
function OnUserPressed(Identifier) {
alert(Identifier);
}
My problems are these: When I press the first value in the table I get "Uncaught SyntaxError: Unexpected token ILLEGAL". When I press any other value in the table I get "Uncaught ReferenceError: xxx is not defined" where xxx is their unique identifier. So it actually retrieves the ID but I still get an error.
Any thoughts?
You probably need to pass the identifier to the OnUserPressed function as a string.
Try wrapping the ${Identifier} template variable with single quotes:
<tr onClick="OnUserPressed('${Identifier}')">
Edit: Responding to comment about single quotes.
Inside your template string you can escape the single quotes by preceeding them with a backslash:
'<tr onClick="OnUserPressed(\'${Identifier}\')">'

Write correctly class name inside onclick of HTML element

I have a class named validate['required'] and I need to put it inside
onclick="something();document.getElementById('something').setAttribute('class',here);"
the problem is that I get a syntax error : missing ) after argument list.
As per your comments I guess you are doing:
onclick="something();document.getElementById('something').setAttribute('class','vaildate['required']');"
The string between onclick="..." is parsed by the JavaScript interpreter of the browser.
Of the JavaScript code, this fails:
'vaildate['required']'
because the JavaScript interpreter will think everything between ' and ' will be your class name, so in your case:
vaildate[
Then the interpreter also reads required']' which it does not know how to handle, thus producing an error.
To literally use the ' character without the browser using it as the end, you can escape it by prepending \:
'vaildate[\'required\']'
Do you mean something like this?
onclick="something();document.getElementById('something').setAttribute('class','validate[\'required\']');"

In JMeter and BeanShell, how can I make a variable lowercase?

In JMeter's User Parameters, how can I make a variable lowercase?
Left column
my_lowercase_variable
Right column
${__BeanShell('${my_variable}'.toLowerCase())} //fails
or
${__javaScript('${my_variable}'.toLowerCase())} //fails
Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.
Note to self.
It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command. Not exactly in the examples unfortunately.
I added the BeanShell Sampler under the Thread Group, then made a variable. No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.
First define a variable in some User Parameters or such
ie:
Name: my_initial_reference
Value: ITS IN CAPS
Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)
Put in:
String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase()); //${blah} = "its in caps" now available
Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.
Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.
Simply can add a function
${__lowercase(${VAL},VALUE)}
${__uppercase(${VAL},VALUE)}
Note: VAL can be correlated or paramiterized value (e.r VAL= TO LOWER or VAL= TO UPPER). We can use this function in beanshell (pre-processor/post-processor/sampler). Jmeter version using (2.6).
Can use it where ever we want in the script as ${VALUE}.
${__javaScript('${foobar}'.toLowerCase())} does work. If the output is ${foobar} instead of desired value, it means that the variable has not been declared
Note that variables are defined only after the "User Defined Variable" component has been parsed. Variables cannot be reused within a single "User Defined Variable" component e.g.:
The second row in that image will not be able to refer to the variable my_variable in the first row. To be able to refer to the first variable, two "User Defined Variable" components is needed. The first variable will be in the first component and the second variable in the second one, e.g.:
With that, ${my_lower_case_variable} will successfully be converted into some value.
${__BeanShell("${my_variable}".toLowerCase())} works too. (Note that Bean Shell requires double quotes. The code in your question uses single quotes.)
Another way is to use vars.get:
${__javaScript(vars.get('my_variable').toLowerCase())}
${__BeanShell(vars.get("my_variable").toLowerCase())}
Hmmmm, your bean shell code didn't work for me. The bean shell sampler returned:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String blah = AAP; vars.put("blah", blah.toLowerCase()); //${blah} now availab . . . '' : Typed variable declaration : Void initializer
I added two double quotes to solve it:
String blah = "${my_initial_reference}";
vars.put("blah", blah.toLowerCase()); //${blah} now available
The beanshell and JavaScript functions in this use will fail, because they don't import the packages you need in order to use .toLowerCase.
If you really need to use a function to convert case (rather then declaring them as lowercase in the first place), you may need to write a full beanshell post-processor script in order to import the needed packages.
http://jmeter.apache.org/usermanual/functions.html#__BeanShell
http://jmeter.apache.org/usermanual/functions.html#__javaScript
http://www.javadocexamples.com/java_examples/org/apache/jmeter/
var blah = "${my_initial_reference}";
blah.toLowerCase();

Categories

Resources