Question Returning a value from a JavaScript function that calls a PageMethod/WebMethod

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
I have an application that uses the WebMethod feature of ASP.NET. My JavaScript loks like the following:

function Solve(data){PageMethods.Solve(data,SolveSuccess,SolveFail);}
function SolveSuccess(result){window.alert(result);}
function SolveFail(error){}

This works fine, and displays the result in an alert just as I would expect. However, the place where I want to use result is outside of the Solve method. I have tried to change the SolveSuccess code to assign result to another variable declared outside of SolveSuccess, such as tempresult=result;, but then when I try to access tempresult it tells me undefined. Does anybody know of a way that I can make the result parameter available outside of SolveSuccess? Any help would be appreciated. Thanks.
--
Nathan Sokalski
 
I have tried to change the SolveSuccess code to assign result to another variable declared outside of SolveSuccess, such as tempresult=result;
I tried this also and it works fine for me. Are you sure the page hasn't done postback (and lost the client side state) since then?
 
I tried this also and it works fine for me. Are you sure the page hasn't done postback (and lost the client side state) since then?

Yes, I am sure the Page hasn't done a postback. First of all, the OnClientClick attribute in my Button control ends with return false; which prevents the button from submitting. Also, I tried adding a breakpoint at the beginning of the Page's Init event, and it did not stop at it when I clicked the button, which it would have if it had posted back.
 
How about the timing? What I did to check this was to use two client buttons, one that called the PageMethods, and in the Success callback did both the alert (to verify and notify when data was received) and do the assignment, and the other button that alerted the value of the assigned page variable. So I knew the data was received ok when I requested the use of the variable. The PageMethods make an async call to server, this is the reason for the mandatory Success/Error callback methods, only after the Success 'event' the returned data is available to client.
 
Back
Top