String from PHP doesn't work in JS - javascript

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

Related

Unexpected token | Parse PHP array to JavaScript

When I am parsing a PHP array which is filled with data from a database to JavaScript, I get an error called unexpected token '<' . The code which selectes data from my database is:
$wagennummern = NULL;
$result = $db->query("SELECT * FROM `Wagenbuch`");
while($row = $result->fetch()){
$wagennummern = $row['Wagennummer'];
}
The code to use this data in JavaScript is:
var wagennummer = <?php echo '["' . implode('", "', $wagennummern) . '"]' ?>;
The Javascript is the line where the error occurs. Can anybody tell me why there is an error and how to fix this?
The particular error message could be caused by a combination of characters that includes a < in the data.
If you want to convert a PHP data structure to a JS data structure, the json_encode, which is compatible with JS. Don't roll your own. Any special character is likely to break your attempt.
var wagennummer = json_encode( $wagennummern );
It might also be caused by the PHP not being executed at all. This would happen if you weren't loading it from a web server, or if you put it in a file with a .js file extension instead of a .php file.
In addition to #Quentin's answer:
I would point out that if your query does not return any row, the variable $wagennummern will be null (first line of your code)
Trying to feed a null value into implode will generate an error, which will be display as HTML, thus creating the unexpected token '<' error.
I would suggest to initialize the $wagennummern variable to an empty array, that way it will not cause any problems if you have no rows.
Another solution would be to check for the variable being !== null

Passing a URL that has spaces inside a javascript function

I am a attempting to pass a URL inside a javascript onclick function but it returns missing ) error on console log, i experiment on it and found out that the URL contains special characters and sometimes spaces that escape the onclick event.
I am getting the url from a PHP script
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
and passing it on a onclick event
Content 1
My question is how to pass a url text inside a javascript function.
You need quotes around the php output in order to pass string to function:
onclick="getContent('<?php echo $actual_link;?>');">
// ^^ ^^
Your missing a '' inside the getContent function.
onclick="getContent('<?php echo $actual_link;?>');">

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.

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

Categories

Resources