Use Server-Side Script to Write Client-Side Script
It's often quite useful to be able to utilize a value
from a server-side variable in your client-side
scripting. While it may seem like a complex
task, it's actually quite easy.
Normally the output from your ASP is in the form
of HTML, but who says it has to be? There's absolutely
no reason your ASP can't send client-side javascript to
your browser just as easily. The following example takes
the value of an VBScript variable on the server and sends
it down to the client by popping it right into the
appropriate place in a client-side confirmation script.
<%@ Language="VBScript" %>
<%
' Let's say we have a variable which holds a value
' indicating someone's age that we got from a
' database or by performing some other calculation.
' For this example I'm just hard coding in a value.
intAge = 26
' In order to utilize this in client-side script we
' need to pass the value from the server-side code
' to the client-side code. We do this by
' Response.Writing it out just like we would if we
' wanted to display it. The only difference is that
' we place it into the appropriatre place inside of
' the client-side script instead of just in the HTML.
%>
<html>
<head>
<title>Server-Side Script to Client-Side Script</title>
<script language="javascript">
<!--
function btnSubmit_OnClick() {
if (document.frmAge.txtAge.value != <%= intAge %>) {
if (confirm('We calculated your age as <%= intAge %>.'
+ ' Are you sure you want to proceed?')) {
return true;
}
else {
return false;
};
};
}
// -->
</script>
</head>
<body bgcolor="#FFFFFF">
<form id="frmAge" name="frmAge">
Age:
<input type="text" id="txtAge" name="txtAge" />
<input type="submit" id="btnSubmit" name="btnSubmit"
value="Submit" onclick="return btnSubmit_OnClick()" />
</form>
</body>
</html>
If you have a tip you would like to submit, please send it to:
webmaster@asp101.com.