I am manipulating the jSON array in the $.ajax function and i got confused with its syntax. There is a error and can't find it.
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/>REMOVE</div>");
}
Error is in the if block and in the 4th line after RS."+value['price']+"</span>\n\ it says missing statement Uncaught SyntaxError: missing ) after argument list. I think the error is in the way I have written onclick="foo(this)"
Any help?
Replace the double quotes with single quotes. You are terminating the string with the double quotes and creating a syntax error:
...<a href='#' onclick='foo(this)' pid='"+value['id']+"'>
The error was due to a quote misuse on the last line: onclick="foo(this)".
You also had two single quotes missing...
(inside the string somewhere... Not causing the actual error, but you would had some errors in the produced HTML later).
You can use the quote of your choice as the string wrapper to append...
And the other for inside the string.
But you have to watch out for not "mixing" them!
One is the string wrapper and the other is part of the string.
if(value['newVar'] === 1){
$productContainer.append("<div id='productBox' class='grid_3'>\n"+
"<a href='product.jsp?id='" +value['id']+ "'><img src='" +value["image"]+ "'/></a><br/>\n"+
"<a href='product.jsp?id='" +value['id']+ "'><span class='black'>" +value['name']+ "</span></a><br/>\n"+
"<span class='black'>By " +value['company']+ "</span><br/><span class='red'>RS." +value['price']+ "</span>\n"+
"<br/><br/>REMOVE</div>");
}
Tricks:
Concatenate your lines using the + sign.
It prevent the inclusion of multiple tabs and spaces inside the string.
It is a better practice than your trailling slash \ at the end of each line.
Make your variables more evident visually, to be able to better see them, like I did above.
It also helps checking for missing or misused quotes.
Related
I am using a string to store some HTML. However, the string needs to have some variables. The method I am using to input this variables is encountering a problem. There are quotes in my HTML. Therefore the string is cutting short where I don't want it to.
base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"
However, I am getting this error.
'vote(' Uncaught SyntaxError: Unexpected end of input
Even if I remove the 2 single quotes in the brackets, I am getting an error.
'vote(Iron Man); return false': Uncaught SyntaxError: missing ) after argument list. NOTE: Iron Man is the value of data[i].
Thanks in advance!
You've got a ' and a " flipped around.
base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"
^^---- flip these two
Template literals can make complicated string concatenations much more readable and less error-prone as it would eliminate the need for most of the " double quotes in your code sample:
base = `<h2>${data[i]}</h2><br><button onclick="vote('${data[i]}'); return false">Vote for ME!</button>`
I search through the numerous questions already asked about the "unterminated string literal" syntax error but found nothing helping me ...
So, I have this Javascript function :
function parametresModal($parametres) {
document.getElementById('remodalTest').innerHTML = $parametres;
};
Then I call this function on a link in my page :
<a href="#" onClick='parametresModal("<?php the_field('description-defi'); ?>");'>TEST</a>
The parameter written here is simplified ; I actually want to add this Wordpress ACF's function among others and HTML markup, but I found the issue was appearing with this particular field (see below).
This "parametresModal" function is supposed to fill the following div with its parameters :
<div id="remodalTest">MyDiv</div>
Problem is the console outputs
"SyntaxError: unterminated string literal"
The Wordpress ACF's field "description-defi" contains a few lines of text with some simple quotes (ex. c'est, l'éviter, ...).
So I tried to escape the quotes with several methods :
$myField = the_field('description-defi');
$myEscape = json_encode($myField);
or
$myField = the_field('description-defi');
$myEscape = addshlashes($myField);
or
$myField = the_field('description-defi');
$myEscape = htmlspecialchars($myField);
Always resulting in the same error.
Do you see where I could be wrong in my code or my way of thinking the thing ?
Thank you very much !
the_field() will output the content of the selected field. If you want to work with a field, you should use get_field() instead.
See: https://www.advancedcustomfields.com/resources/the_field/
Also the newline character will not be escaped by any of PHP's escape functions, if your String contains newlines, you will need to escape them manually using something like this: $myField = str_replace(array("\r\n", "\n"), "<br>", $myField);.
If you know that your DB will consistently use the same newline sequence, you can replace array("\r\n", "\n") by that newline sequence instead.
I get the syntax error when I try to pass the following string:
JSON.parse("[{\"Date\": \"4/4/2016 4:15:19 PM\", \"Message\":\"<h3>New
Message</h3> Generated at 4/4/2016 4:15:19 PM.<br/><br/>Heavy Responsive
URL: <a href=\"https://performingarts.withgoogle.com/en_us\" ></a><br/><br/>
<img src=\"https://s-media-cache-ak0.pinimg.com/236x/06/bd/ac/06bdacc904c12abdce3381ba1404fd7e.jpg\" /> \"} ]");
I know that the error come from the link when I use double quote.
If I use single quote then no issue, but the data is getting from server side, I got no control over what going to pass in so I can only control on my side.
From what I read from the internet so far, I tried the following:
Use JSON.stringify first, then only use JSON.parse. I can parse
with no issue but problem occur when I try to loop the data. Instead
of looping it as JSON, the loop take the data as string and loop
every single text.
Escape every double quote which I'm currently doing, but it's not
working as shown above. But if I replace every double quote to
literal, I'm afraid some of the message that suppose to be double
quote will turn into literal as well, which will result in weird
looking message.
Please advice what other alternative I have to solve this.
You have JSON embedded in a JavaScript string literal.
" and \ are special characters in JSON and are also special characters in a JavaScript string literal.
href=\"https: escapes the " in the JavaScript string literal. It then becomes a " in the JSON. That causes an error.
When you want the " as data in the JSON you must:
Escape the " for JavaScript (as you are doing already)
Escape the " for JSON by adding a \.
Escape the \ for JavaScript
href=\\\"https:
I'm contributing to a javascript framework which has the equivalent of the following code:
eval("'" + user_input.replace(/'/g, "'") + "'");
I know this is terrible -- no need to persuade me. What I want to know is, can I inject arbitrary code here?
At first glance the user_input.replace("'", "'") would seem to prevent me from breaking out of the string. However I can pass in newlines e.g. \nalert(123)\n, but then the result is always a syntax error, e.g.
'
alert(123)
'
Is there actually a vector for code injection here, other than just causing a syntax error?
While this is undoubtedly a worrisome pattern, it's safe if used exactly in the way described. The only character that can terminate a single-quoted string in Javascript is the single quote character. So long as that character does not appear in the string interpolated into the single quotes, it cannot possibly be interpreted as anything other than a string.
About the worst thing I can think of that you could do is end a string with a backslash, which would result in an unterminated string, e.g. if user_input were:
example\
then the evaluated code would be
'example\'
which would result in a syntax error, because the string contained in the eval is never terminated. However, if the real eval is actually more complex, this is exploitable. For example, if the code were:
var escaped_input = user_input.replace(/'/g, "&39;");
eval("'" + escaped_input + "' some more stuff '" + escaped_input + "'");
then it could be exploited with an input like:
; alert(1); // \
which would result in:
'; alert(1); // \' some more stuff '; alert(1); // \'
^^^^^^^^^
in which the underlined content would be evaluated, because the quote that was supposed to exit the string was escaped, turning the next single quote into a closing quote! To be safe, I'd recommend escaping or replacing backslashes if possible (unless you're explicitly trying to use eval() to deal with them, in which case you might just catch the exception).
echo '<a onClick="articleDeleteConfirm("'.
$row["title_$lang"].'","'.$_GET["editPage"]).'">';
The main problem is with: $row["title_$lang"], I have to use $lang variable inside. " and ' just not enough.
The problem you describe actually has nothing to do with your PHP variables, those are all being output as expected. The problem is that you need to escape the " inside of the <a> and you've misplaced a ).
Your original would output:
<a onClick="articleDeleteConfirm("value1","value2">
That is not valid HTML (even the highlighter dislikes it). Now, notice the \'s in the following (and that the paren was moved into the string).
echo '<a onClick="articleDeleteConfirm(\''
.$row["title_".$lang."].'\',\''.$_GET["editPage"].'\')">';
The escaped version outputs:
<a onClick="articleDeleteConfirm('value1','value2')">
It uses single quotes inside of double quotes to provide easy to read (and valid) html. Now, you have another issue with your code.
Any time you output a $_REQUEST variable to the browser, you risk something called cross-site-scripting. Someone could put JavaScript into $_GET["editPage"] and it would smell bad. The easy way to avoid it? Use htmlentities($_GET["editPage"])
I had same problem too, I don't know exactly why but I had syntax error no matter what I did, So I tried this and got answer.
The problem is that you're using a double quotation to open onClick and again you're using another double quotation to open an string.
Use this and you'll get answer.
echo '<a onClick="articleDeleteConfirm('.char(39).$row["title_$lang"].char(39).','.char(39).$_GET["editPage"]).char(39).'>';