Tutorial :How does ASP.NET AJAX work when retrieving values from the server?



Question:

If I want to call a server function from javascript to retrieve a name of a person from a database (just as an example)... and I went...

name = myServices.getName(userId);

If I have a script manager with a service reference to a .asmx file that has the web method getName( int userId ) {} then this function should be called properly and would, eventually, return the name for that userId.

Unfortunately I want to do....

name = myServices.getName(userId); alert(name);

however, when doing ASP.NET AJAX, it would call the web method and continue executing before waiting for a response from the server (which I understand is the point of ajax, to stop the browser from freezing while waiting for data)

I need to get the name back from the server before I can continue executing... How can I approach this to fix this issue?


Solution:1

There is method you can add as a parameter to the service method that will call the method on success where you can do other stuff.

For example:

function test(){            PageMethods.MyMethod("name", OnMyMethodComplete);        }            function OnMyMethodComplete(result, userContext, methodName)        {          alert(result);        }  


Solution:2

If you want to call a web method synchronously, you'll need to set up the request manually, and use a Sys.Net.XMLHttpSyncExecutor.

Here's an example (see ExecuteSynchronously function)


Solution:3

For a javascript solution, you could loop until name has a value. Adjust time based on latency to keep app responsive

var time = 100;  window.setTimeout(name = '' ? wait : continue, time);          function wait()  {      window.setTimeout(name = '' ? wait : continue, time);  }  function continue()  {      //code having to do with name      alert(name)  }  


Solution:4

congratulations. you've taken your first step into a larger asynchronous world. I'd definitely go with using the callbacks that CSharpAtl suggested.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »