0

I am developing application which will get some dynamic content which is irrelevant to my question. and the question is

 var pat;
 $.post('venki/path.jsp', { nam:nam } , function(data) {
     pat=data;
     alert(pat); //it will displayed the received code form path.jsp   
 });
 alert(pat);// it will not keep the data received from path.jsp

Now I need to not lose the scope.

For example:

var pat=0;

$.post(
     pat = 1    
);

alert(pat);

It should alert 1 and not o

In java, i should use static. In jquery, how to declare static variables.

Got an answer: Its simple and very useful and no need to worry about synchronous. the answer is tricky...

itsme
  • 135
  • 3
  • 5
  • 15
  • 1
    Another duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Mar 25 '14 at 10:10
  • 2
    This has nothing to do about scope and everything to do about timing. Asynchronous JavaScript And XML is **asynchronous** – Quentin Mar 25 '14 at 10:10

2 Answers2

4

it is because post request is not completed when you are alerting pat value. To ensure that value is modified, alert it inside post success function:

var pat;
 $.post('venki/path.jsp', { nam:nam } , function(data) {
    pat=data;
    alert(pat); //modified value   
  });
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • yes, it will surely work if we give inside the scode..i need to use the variable value inside my project for other usages...any idea? – itsme Mar 25 '14 at 10:12
  • 1
    setTimeout is another approach but i would suggest you not using it because you can not predict the time required for completion of request. Time required for request completion depends on lots of factor live server load, connection speed etc... – Milind Anantwar Mar 25 '14 at 10:14
  • 2
    Once the async call completes, pass the data to another function and use it? – user1329482 Mar 25 '14 at 10:41
3

If i'm not mistaken, the $.post is async so the pat is not losing it's scope but executed before the pat=data executed

To make it synchronous call look at this question: how to make a jquery "$.post" request synchronous

Community
  • 1
  • 1
imkrisna
  • 853
  • 5
  • 7