views:

771

answers:

4

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?

+3  A: 

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);

    }
CSharpAtl
I do this sort of thing all the time. Saves me lots of trouble.
Adam McKee
A: 

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)

Phil Jenkins
A: 

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)
}
s_hewitt
A: 

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

marduk