Search code examples
javascripthtmlasp-classic

How to use an ASP variable in Javascript?


As the title says, I'm just trying to use an ASP variable in Javascript, but the code that I have is not able to do so. How do I achieve this?

<%
    dim strMyString
    strMyString = "hello there"
%>

<HTML>
<body>

    <%=strMyString%>
    <p id="demo"></p>

<script type="text/javascript">

    document.getElementById("demo").innerHTML = <%=strMyString%>;

</script>

</body>
</html>

The only output I am getting is "hello there". Expected output is "hello there" twice.

Any help is appreciated.


Solution

  • Your example generates the following on the client:

    document.getElementById("demo").innerHTML = hello world;
    

    This is obviously invalid JavaScript and will therefor throw a syntax error (check the console).

    You have to wrap the string in quotes:

    document.getElementById("demo").innerHTML = "<%= strMyString %>";