Hi Guys,
I was working on an ASP.NET page and found a strange problem. Whenever i
was calling the jquery ajax POST request, The data from webservice was
available in the success function but not after $.ajax request code. This
was strange i as wanted to access the data after calling the ajax POST
request.
Here is the problem
var localdata;
$.ajax({
data:"{'id':'1'}",
type:"POST",
dataType:"json",
contentType:"application/json",
url:"http://www.test.com/test.svc/HelloWorld",
success:function(data){localdata=data;alert("Inside Success "+localdata);},
error:function(a,b,c){}
});
alert("After ajax "+localdata);
After executing the above it gave me "Inside Success Hello", But the second
alert message gave me "After ajax undefined". This was due to the fact
that the first call was made inside success which was asynchronous, Whereas
the second alert was not asynchronous and didn't wait until the
$.ajax POST request executed.
To solve the same, I made it synchronous as i had to store the result of
webservice in a local variable, Here is the code
var localdata;
$.ajax({
data:"{'id':'1'}",
type:"POST",
dataType:"json",
async:false, //setting this made it a synchronous call
contentType:"application/json",
url:"http://www.test.com/test.svc/HelloWorld",
success:function(data){localdata=data;alert("Inside Success "+localdata);},
error:function(a,b,c){}
});
alert("After ajax "+localdata);
Thanks
Ritesh Tandon