1

I want to access variables defined in Javascript in.aspx file to .aspx.vb file

How can i access variables in .aspx.vb file?

<script type="text/javascript" language="javascript">
   var c=0;
   var m=0;
   var h=0;
   var t;
   var timer_is_on=0;
   function startTMR()
   {  
      document.getElementById('TimeLable').value=h+":"+m+":"+c;
      c=c+1; 
      if(c==60)
      {
         c=0;
         m=m+1;
         if(m==60)
         {
            m=0;
            h=h+1;
         }
      }
      t=setTimeout("startTMR()",1000);
   }

   function doTimer()
   {
      if (!timer_is_on)
      {
         timer_is_on=1;
         startTMR();
      }
   }

This is simple javascript I'm using in my .aspx page

now i want to access the variable h m and c in .aspx.vb page how to do that?

1 Answer 1

2

You'll need to save that javascript variable into a hidden input, which will post with your form when you do a postback. You'll be able to access the value via:

string value = Request.Form["hiddenName"];

Assuming you declare your hidden input like this:

<input type="hidden" id="hiddenValue" name="hiddenName" />

You can set this value like this with native JavaScript:

document.getElementById("hiddenValue").value = "12";

or with jQuery like this:

$("#hiddenValue").val("12");

If you'd like to make sure this hidden input is automatically saved to the JavaScript variable x before you post back, you could do the following with jQuery

$("#form1").submit(function () {
     $("#hiddenValue").val(x);
});

Or this with native JavaScript:

document.getElementById("form1").addEventListener("submit", function () {
       document.getElementById("hiddenValue").value = x;
});

If you're not using jQuery, and you opt for this native option, just make sure you put the script at the bottom of the body section; do not put this script in the head, since the dom is not formed yet, and you will get a null error.

And obviously this all assumes your form element looks like this:

<form id="form1" runat="server">

if yours has a different id, then adjust accordingly.

Sign up to request clarification or add additional context in comments.

4 Comments

request.form was givin me error so i put <asp:HiddenField ID="hidt" runat="server" /> as hidden input and from .aspx.vb i got the value from hidt.Value.ToString()
@chetan - that's even better - I should have thought to put that. Glad you got it working.
now plz tell me how to call backend function from javascript? In my example i want to call backend function when c==60
You'll need to use ajax somehow. jQuery will help a great deal too. You'll want to set up a web service or static page method, then send requests to it via $.ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.