Uncaught ReferenceError JavaScript - 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}\')">'

Related

JavaScript escape sequence cannot read a variable value while concatenation?

I am working in a Laravel application. I want to concatenate a variable with a string using escape sequence (` `) in JS. A normal concatenation of strings and variable work fine using escape sequence. But it does not work and throws error when I concatenate PHP route string with a parameter. You will have an idea when you see the below code.
<script>
function changeStatus(value, applicationId){
var url = `"{{route('application.toggle.approval',['id'=> ${applicationId} ])}}"`;
console.log(url);
}
</script>
I am not being able to pass any kind of variable there. It is giving me error like below:
(2/2) ErrorException
Use of undefined constant applicationId - assumed 'applicationId' (View: C:\wamp64\www\oibn\app\Modules\Application\Views\applicationShowProtected.blade.php)
How do I pass the variable there? I can console.log the parameters passed in the function. But that value is not getting passed in concatenation. It gives error only. Please help.

String from PHP doesn't work in JS

I'm getting the string from controller:
var x = '<?php echo addcslashes($this->x, "'") ?>';
The parsed result is:
var x = '<script>alert(\'x\')</script>';
Error:
Uncaught SyntaxError: Invalid or unexpected token
I tried to assign the string directly from JS and it works.
The alert is coming up because the first character in the alert is a slash (the unexpected token) the second slash escapes the ' so the alert never closes either.
Not really sure what you're trying to achieve honestly with the script tags etc seems as you're already inside a script when it gets called (unless you're printing it to a page, in which case you're better off adding it to an event handler or something.)

Onclick-function on elements in Handlebars-template

I'm building a simple webapp with just Handlebars.js and some jQuery.
Now I have a list of data, and i present them through a Handlebars-template. Then I want some actions associated with these, e.g. update one element, or delete one. I have buttons that one associates with these actions, the problem is that I cannot manage to get onclick-methods associated with buttons in the template to work.
I read this question and answer, which lead me to adding the extra bracket and helpermethod, but it still doesn't work. See code below.
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
var myGreatFunction = function(someValue) {
// Work with that value
}
The template:
{{#each Something}}
<button onclick="myGreatFunction({{{json this}}})"></button>
{{/each}}
Now, doing it like this give me Uncaught SyntaxError: missing ) after argument list at the top of the HTML-file.
I noted the answer here, so I tried with onclick="myGreatFunction( '{{{json this}}}' )" which gives me the error Uncaught SyntaxError: Unexpected token ILLEGAL at the end of HTML-file.
With onclick="myGreatFunction( '{{json this}}' )" the button simply disappears on click.
Does anyone see something I've missed, or is there another way of doing this? I thought of adding the object to some div/button in the template, then add a jQuery-listener for the click that fetches the value from the template, but that seems so ugly and unclear.
Any tips? All help is greatly appreciated - thanks in advance.
UPDATE: Seems the problem is, as Hacketo mentioned below, that the outputted JSON is kind of messed up. I inspected an element in my code:
onclick="someFunc('{"id":5,"publisher":null,"message":" asdadsad","address":"asdad","published":&quot
Last Saturday at 12:00 AM","createdAt":"2015-07
23T09:55:35.486Z","updatedAt":"2015-07-23T09:55:35.486Z"}')"
(Broken over multiple lines for your convenience).
Now I just have to find out of to get that JSON to look right.
This is because JSON.stringify return a JSON string and contains ".
At the moment, your template may look like this:
<button onclick="myGreatFunction({{{json this}}})"></button>
Compiled :
<button onclick="myGreatFunction({"foo":"bar"})"></button>
^ ^ ^ ^ ^ ^
And this result as
Uncaught SyntaxError: missing ) after argument list
You need to escape those " and you can do this in your helper
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context).replace(/"/g, '"');
});
And this will result as
<button onclick="myGreatFunction({"foo":"bar"})"></button>
Just take out the extra bracket. If you let Handlebars do HTML escaping (which it will automatically on a regular {{json this}} invocation), it will also escape the quotes for you.

passing Illegal Token to javascript function?

I'm trying to pass a variable that looks like 68679786987698_987687697869786 to a function in Javascipt, but I'm getting the error Uncaught SyntaxError: Unexpected token ILLEGAL in Chrome's developer console. It looks like the underscore is the problem, but I need it to stay there. Any suggestions?
Here's the relevant code:
entry += '<span>Like';
function likePost(id) {
alert('like');
}
Use quotes:
entry += '<span>Like';
post.id must be a string if it contains the underscore.

SyntaxError: identifier starts immediately after numeric literal in Firebug

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.

Categories

Resources