user14647440
user14647440

Reputation:

SyntaxError javascript php

This is a heart with a wishlist, I want to add the product to my wishlist.

I have a syntax error in the console

Uncaught SyntaxError: expected expression, got '}'

Dreamweaver shows me no errors

<div>
  <i id="id'. $result->id .'" 
     class="far fa-heart cart_heart" 
     onClick="add_to_wishlist("' . $result->id . '", "add")">
  </i>
</div>  

<script>
   function add_to_wishlist(id) {
      alert(id);
   }    
</script>

HTML output

<i id="id17254" 
   class="far fa-heart cart_heart" 
   onclick="add_to_wishlist(" 17254",="" "add")"="">
</i>

php output with html (need to ajax)

    if(empty(h($result->id)))
    {  }
    else 
    {
        $html .= '
            <td width="30%"><label>Heart:</label></td>  
            <td width="70%">
            
            <div>
            <i id="id'. $result->id .'" class="far fa-heart cart_heart"
            onClick="add_to_wishlist(' . $result->id . ', 'add')"></i>
            </div>  
            
            </td>  
        </tr>
        ';  
        }

    $html .= '</table></div>';

echo $html;

Upvotes: 0

Views: 42

Answers (1)

Not A Robot
Not A Robot

Reputation: 2684

Not having clarity over the code, it is somewhat difficult to tell the main cause of the error, as according to the error you are getting is

Uncaught SyntaxError: expected expression, got '}'

There is a code of block that is ending with these curly braces }

Also, you need to escape characters to make your code work properly.

$r = 1; //I am assuming this for simplicity

$html ='
     <div>
        <i id="id'.  $r  .'" class="far fa-heart cart_heart"
           onClick="add_to_wishlist(\'' .  $r  . '\', \'add\')"></i>
      </div> ';  

echo $html;

The above code produces this HTML code

<div>
   <i id="id1" 
      class="far fa-heart cart_heart" 
      onclick="add_to_wishlist('1', 'add')">
   </i>
</div>

You need to escape characters(\') to work around single quotes(') that is in your PHP code.

 onClick="add_to_wishlist(\'' .  $r  . '\', \'add\')"

Here adding \' helps in formatting parameters correctly.

Upvotes: 1

Related Questions