1

Here is the problem which I am facing.

 echo "<script type='text/javascript'>window.insertCartInHeader({$cart});</script>";

$cart variable is holding HTML block of code. I get Uncaught SyntaxError: Unexpected token <

Solution?

window.insertCartInHeader = function(cart){ 
    console.log(cart)
    var list = $("#top-links").append('<ul id="cart-header"></ul>').find('#cart-header');
    list.append('<li>'+cart+'</li>');
}

Here is the string which I am passing

'<div id="cart">


  <button type="button" data-toggle="dropdown" data-loading-text="Loading..." class="heading dropdown-toggle">

  <div class="pull-left flip"><h4></h4></div><span id="cart-total">0 item(s) - £0.00</span></button>


  <ul class="dropdown-menu">


    <li>

      <p class="text-center">Your shopping cart is empty!</p>

    </li>


  </ul>

</div>

' (length=402)
3
  • Why the curly braces? Strings are wrapped in quotes. Commented Feb 6, 2017 at 15:40
  • show insertCartInHeader please Commented Feb 6, 2017 at 15:40
  • Did you just edit your question but ignore my comment...? Commented Feb 6, 2017 at 15:44

1 Answer 1

2

You need to add quotes ("), to let javascript know it's a string, and you should use addslashes, since you may have classes or attributes in that html.

echo "<script type='text/javascript'>window.insertCartInHeader(\"". addslashes($cart) . "\");</script>";

Without addslashes something like this, won't work:

$html = '<h1 class="hi">It works</h1>';

For multiline html, this should work.

str_replace("\n", "\\", addslashes($cart)); 

You can improve that replace, but you get the idea.

Sign up to request clarification or add additional context in comments.

4 Comments

Uncaught SyntaxError: Invalid or unexpected token
I tried it with my HTML, and it works, post the entire string in $cart.
@Nikanor I believe you're still having an Issue because your code is multiline. you need to escape newlines with "\".
just succeded with tilda characters around {$cart}. Thanks for the tip, yea multiline is the problem here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.