Adding variables in string JS - javascript

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>`

Related

How to make string to json object

I have below string
'[{\'Question\': \'a Names and Roles (if known)\'}]'
I need to convert it into JSON.
I tried JSON.parse(s)
I got error SyntaxError: Unexpected token ' in JSON at position 2
and also
> eval(s)
SyntaxError: Unexpected string
Any help would be really appreciable
Problem is that you need to pass string inside JSON.parse(s).
Please make sure s is a string
'[{*Question\': at the point of asterisk you need a \' don't you?
So it should be
'[{\'Question\': \'a Names and Roles..
EDIT
Found this after a bit of research. Problem is with the single quote. Replace them with double quotes, you are good to go. See this fiddle, to check this out in action.
Additionally, I had to modify "[\'NA\']" in your string, to get it to working. That is also invalid JSON. If it is an array that you want it to be, you should put it like [\"NA\"].

html syntax error in jQuery.ajax funciton?

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.

Uncaught Syntax Error: Unexpected Identifier Value (include percent sign) Javascript

I am trying to assign the value to variable in simple Java Script but getting "unexpected identifier" error, I feel that the% signs are creating problem here.
Any suggestion please?
You need to surround strings with quotes (' or ")
the value you are assigning to the rid is string.
So, always use Quotes
'or"

JSON.parse get "Uncaught SyntaxError: Unexpected token h"

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:

Error due to single quote ' in javascript function call

I am passing value dynamically to javascript function.
I am retrieving data from database and filling to javascript function, it does not have a static binding.
share_it(data_from_mysql_database);
like
share_it('value from mysql database');
Some times value contain a single quote (').
like:
share_it(' Essentially you'll have to have a good academic history ');
So function call gives error that:
Uncaught SyntaxError: Unexpected identifier
You can use the \ character to escape such characters:
share_it(' Essentially you\'ll have to have a good past academic ');
Or, you can switch to using double quotes if you know you will need to embed a single quote character:
share_it(" Essentially you'll have to have a good past academic ");
You can freely switch between double " and single ' quotes where you need the other in a literal string:
share_it(" Essentially you'll have to have a good past academic ");
Only in cases where you need both, you need to escape the repeating character:
share_it(" Essentially you'll have to have a good \"past\" academic ");
You can also replace the ' in the string with &#39.
You ought to be converting special chars on the upstream rather than the downstream. Converting it on the upstream saves time later when an inexperienced developer does not care to escape the data on the downstream when sent to the client. Since you have not properly converted the data on the upstream, you have no choice. You should escape it.
share_it(escape(data_from_mysql_database));
Example"
> escape("You're awesome");
'You%27re%20awesome'
>

Categories

Resources