Tuesday, 16 April 2013

ASP: pass a variable to JavaScript

   


One of the most often asked question in forums is "how do I pass an ASP variable to JavaScript?"
It is quite common to find out that people ask the question the other way round: "How do I pass a JavaScript variable to ASP?"
Ok, the two things are completely different and they involve completely different solutions.

First of all, let me explain something you might already know. ASP (or to be precise VBScript) is a server side language, while JavaScript is a client side language. The two work on different levels: ASP is executed before the page is completely loaded, while JavaScript works only after that. For that reason we cannot pass a JavaScript variable to ASP without reloading the page.

Say that, if we need to convert a JavaScript variable to ASP, we need to pass it using the page URL and get the variable or use a form a submit an hidden value. Those are simple solutions, but - I must say - not really elegant solution.
Let's see an example. The JavaScript part (to be inserted in the head of the document) could be something like:
<script language="javascript">
function GetHidden()
{
document.form1.action="http://YourPageName.asp";

document.form1.submit();
}
</script>
The HTML part could be:
<form id="form1" runat="server">
<a href="#" onclick="GetHidden();" >Click Here</a>
<input type="hidden" id="txt1" name="txt1" value="ourTestValue" />
</form>
And finally our ASP code:
<%
dim strVal
strVal=Request.Form("txt1")
%>
What about the other way round: pass an ASP variable to JavaScript. Well, that is much much easier!
Suppose our ASP variable is "ASPVariable" and our new JavaScript variable is "JSVariable", the JavaScript code would be:
<script language=javascript>
var JSVariable = <%=ASPVariable%>
</script>
Simple as that.

I hope you find the post interesting enough. Keep on following the web thought.

PS: this is the 400th post! Wow, I couldn't believe it when I saw it.

1 comment:

  1. Great explanation. Thank you!

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.