PVP
PVP

Reputation: 165

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/><a href='#' onclick="foo(this)" pid="+value['id']+">REMOVE</a></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?

Upvotes: 0

Views: 37

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

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/><a href='#' onclick='foo(this)' pid=" +value['id']+ ">REMOVE</a></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.

Upvotes: 0

KAD
KAD

Reputation: 11102

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']+"'>

Upvotes: 1

Related Questions