Search code examples
javascriptvariablescode-behind

passing variables from code behind doesn't work in Firefox


I am successfully able to pass variables from code behind to javascript in IE, but not in firefox. What I do is I have these public variables in my code behind: public string passedVar = ""; and it gets assigned to a value in the page load event: passedVar = "In code behind";

and then in the aspx page, inside a script block, I do this: var clientVar = "<%= passedVar %>";

and then I am able to access it in other js files of that page just fine... in IE only!

If I am using javascript; however, that variable in the .js is showing up as "undefined"

I can find alternate values like hiddenfield, but I want to know why this is not working like it should!

thank you!


Solution

  • If you need to process data through Javascript, do an ajax call (sync or async) to an empty .aspx page (I mean code-behind only), get the data result on success event and process the data in the callback function. Some code based on JQuery samples:

    $.ajax({
      type: "POST",
      url: "http://myDomain/myPage.aspx",
      data: "par1=val1&par2=val2",
      async: false,
      success: function( data ) {
           /*
            * data contains the myPage.aspx response
            * it could be a single value or a comma-separated list of values
            * initialize passedVar or whatever
            */
    });