Amazon Ad

Monday 26 May 2014

jQuery ajax POST and saving value in local javascript variable


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

No comments:

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...