Reputation: 262
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)
Upvotes: 1
Views: 41
Reputation: 40434
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.
Upvotes: 2