0

I have this code:

<%If CInt(Request.QueryString("OpenYouthHistory")) > 0 Then %>
<script>
    var yid = <% Request.QueryString("OpenYouthHistory") %>;
    window.open("YouthHistory.asp?YouthID=" + yid);
</script>
<% End If %>

I want to open the YouthHistory.asp page in a popup window if the OpenYouthHistory query string variable is set. However when I run it with a value of, say, 210, then I get this output:

<script>
    var yid = ;
    window.open("YouthHistory.asp?YouthID=" + yid);
</script>

Which of course is invalid JavaScript. But why is the yid variable not getting a value? If the query string variable really is blank, why is the <script> tag even rendering? I'm so confused...

ekolis
  • 6,270
  • 12
  • 50
  • 101

1 Answers1

2

Use <%= which is a shortcut for <% Response.Write

<%If CInt(Request.QueryString("OpenYouthHistory")) > 0 Then %>
<script>
    var yid = <%=Request.QueryString("OpenYouthHistory") %>;
    window.open("YouthHistory.asp?YouthID=" + yid);
</script>
<% End If %>
user2316116
  • 6,726
  • 1
  • 21
  • 35
  • Aha, thanks! Totally forgot about `<%=`! – ekolis Mar 24 '20 at 19:48
  • One thing I will say when working with injected ASP variables surround them with quotes so if they are empty it doesn't cause a syntax error in JavaScript. Something like `var yid = "<%=Request.QueryString("OpenYouthHistory") %>";`, that way you can use JavaScript to check the length of `yid` to see if it contains a valid value rather than `var yid = ;` causing a syntax error. – user692942 Mar 25 '20 at 10:42
  • 2
    your comment makes sense however there is `<%If CInt(` in front of it, so only numeric value will go to the injected code. – user2316116 Mar 25 '20 at 12:06
  • @alex it does, I did notice that but as OP focused in on the `<%=` I wanted to make the point clear about making sure values are valid before attempting to inject them. The answer is absolutely right, it wasn't a criticism. – user692942 Mar 26 '20 at 07:49
  • 1
    while I fully understand your comment, we should not confuse OP telling about syntax errors as values will not be necessary invalid without quotes - javascript specification doesn't require quotes for numeric literals and `var yid = 1;` will be absolutely valid from any point of view. – user2316116 Mar 27 '20 at 09:34