JavaScript function, pass HTML as parameter
16,465
Solution 1
Here's problem:
myHTML is a HTML string like this:
var myHTML ="<div id="foo"><div id='hello'>hello</div><div id="bar">bar'asdf'asf"sdf"&soidf;</div></div>";
That won't work because you have quotes and stuff inside it that are NOT escaped.
If you used innerHTML
to get the HTML of an element on the page, this wouldn't be a problem.
Solution 2
myHTML is constructed with some < or > extra so verify the html string
Author by
sf89
Updated on June 04, 2022Comments
-
sf89 about 2 years
I have two functions in my script, one that outputs some long HTML string, the other one that takes this string as a parameter and processes it.
function myFirstFunction() { //output some HTML return myHTML; } var myHTML = myFirstFunction(); function mySecondFunction(myHTML) { //do something with parameter }
For some reason that I can't figure out, the Chrome JS Console keeps giving me the following error: "Uncaught SyntaxError: Unexpected token <"
I thought maybe that was due to the fact, that the outputed HTML was pretty long since it seems to be working with small chunks of HTML. Any thoughts? Thx!
-
sf89 almost 12 yearsI have, and really can't see extra "<"... Is there a tool that could double check for me?
-
sf89 almost 12 yearsThis is an ajax context. So I have: <?php header("Content-type: text/javascript"); ?> var string = "<?php echo $myHTML ?>"; receiveMessage(string); As you can see, I am putting quotes as I think they should be. Or is it wrong?
-
sf89 almost 12 yearsIs there a way I can escape them? I don't see how I can use innerHTML to serve that purpose... thanks for your help
-
saml almost 12 yearsI don't know what the contents of $myHTML, so I have literally no idea what needs to be escaped. Can you just post what the contents of $myHTML are as it exists on the PHP side? You may need to escape it on the php side
-
sf89 almost 12 yearsOutput of the function on the php side: echo '<div class="box_img"> <img src="myLogo.png"/> </div> <div class="new_box"> <div class="triangle_left_2"></div> <div class="triangle_left_1"></div> <div class="username">USER</div> <div class="rt-button"> <a href="twitter.com/share" class="twitter-share-button" data-count="none" data-lang="en" data-text="'.$a_first_var.'">ReTweet</a> </div> <div class="txt_item"><p>'.utf8_decode($some_var).'</p></div> </div>';
-
saml almost 12 yearsTry wrapping that call to utf8_decode() in htmlspecialchars()
-
Santiago Elvira Ramirez almost 12 yearsopen one new html file and copy there the html then you check it
-
sf89 almost 12 yearsthanks! I tried it, but it seems my html is clean so the error doesn't might not come from it
-
sf89 almost 12 yearsI just tried that, but it's throwing me "Uncaught SyntaxError: Unexpected token & "
-
rxgx about 9 years@sf89 add slashes before the quotes to escape them from normal code; example:
var html = "<div class=\"container\"></div>";