0

I'm trying to get the following Javascript work (it should be an embedded survey from formstack.com that shows up on specific days). However, when I try to view it all I get displayed is the string (without the quotes) "'); }" What is wrong?

<head>
<script type="text/javascript">

var theDate = new Date();
var dayOfWeek = theDate.getUTCDay();

// Returns true if the restaurant is open
function isOpen()
{
    //I'll fill this in later, for now, return true
    return true;
}
</script>

</head><body>
<script type = "text/javascript">
if(isOpen())
{
document.write('<script type="text/javascript" src="http://www.formstack.com/forms/js.php?1134414-uqmj2UXxEw-v2"></script>');
}
</script>
</body>
user950891
  • 953
  • 3
  • 10
  • 13

4 Answers4

2

You can't have a string containing '</script>' inside a SCRIPT element. Consider loading additional scripts like so:

var script = document.createElement( 'script' );
script.src = 'http://www.formstack.com/forms/js.php?1134414-uqmj2UXxEw-v2';
document.body.appendChild( script );

Your preferred JavaScript library probably contains a dedicated function for this. For instance, I use jQuery, where it's done like so:

$.getScript( 'http://www.formstack.com/forms/js.php?1134414-uqmj2UXxEw-v2' );
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
2

Don't have a </script> tag in your string, that ends the script tag.

document.write('<scr'+'ipt type="text/javascript" src="http://www.formstack.com/forms/js.php?1134414-uqmj2UXxEw-v2"></scr'+'ipt>');
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • So why do you break up the ` – Jared Farrish Nov 06 '11 at 00:13
  • @JaredFarrish: Just to be on the safe side. It works simply because `` is not interpreted as an ending tag for the script. – Guffa Nov 06 '11 at 00:27
  • Just wondering... Why does JS interpret a script tag in a string as the ending tag for the calling statement? (Which is what I think you're saying, right?) – Jared Farrish Nov 06 '11 at 00:36
  • @Guffa I believe it's the constucte `` that has to be guarded against, per spec, but this is likely guarded to only need to protect against `` in modern browsers. ` –  Nov 06 '11 at 00:44
  • 1
    @JaredFarrish: Because the HTML tags are parsed before the script. – Guffa Nov 06 '11 at 01:11
0

I've heard stories of javascript failing to execute inside document.write... try breaking it up:

document.write("script type = " + "text/javascript" + "src='http://www.formstack.com/forms/js.php?1134414-uqmj2UXxEw-v2'>" + "/script"); 

(greater and less than signs removed, you should know where to put them)

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
Techboy6601
  • 110
  • 1
  • 11
-1

I wonder if the / of is being see as the escape character. Something that you can try is

String s = @"...." where .... is the text.

The @ tells the compiler to treat everything in "'s as a literal. I know that this works in both C# and Java. I am not 100% sure about javascript.