Tuesday, September 29, 2009

.Net 3.5 - Asp.Net AJAX - Sys is undefined

I was trying to check the events of PageRequestManager when I came across the "Sys is undefined" error in javascript. I came across a galore of suggestions to fix this thing up but all seemed a bit weird. Many people pointed fingers at IIS and I was using the in-built web server to run my app. Others were discussing about .Net framework 1.1 or 2.0 which didn't have AJAX built-in and thus suggested modifications in the web.config. But here's what I found:
If you're using .Net framework 3.5 then AJAX is built into the system and you shouldn't be required to update the web.config. I was reading the chapter on AJAX when the author mentioned that an event is raised when all the AJAX initializations are finished. This event is pageLoad() (Not to be confused with pageLoaded event of PageRequestManager). The problem "Sys is undefined" was coming when I was declaring a global variable that gets the instance of PageRequestManager using Sys.WebForms.PageRequestManager.getInstance(). But this was not available as the AJAX framework hadn't finished loading. So, if you need to attach event handlers to PageRequestManager do it in the pageLoad() function.

Here's the problem code:

<script type="text/javascript" language="javascript>
var prm =Sys.WebForms.PageRequestManager.getInstance();
//This is global as prm is used by many functions but this is wrong...
//AJAX framework is not loaded yet so it throws a violation right here

function bindEvents()
{
prm.get_initializeRequest(InitializeRequest);
}

function InitializeRequest(sender, args)
{
if(confirm("Do you wish to abort request?"))
{
prm.abortRequest();
}
}
</script>

Here's how to correct this:

<script type="text/javascript" language="javascript>

//Name of this function is very important. This is a particular event
//that runs when AJAX framework has finished loading all the scripts
function pageLoad()
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.get_initializeRequest(InitializeRequest);
}

function InitializeRequest(sender, args)
{
if(confirm("Do you wish to abort request?"))
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.abortRequest();
}
}
</script>

1 comment:

  1. Thank you so much! Helped me solve an irritating problem.

    ReplyDelete