0

I try to get data after success ajax but it is not work correctly, please help me.

var aid='11111111V';
var dch=0;
  $.ajax({
  type:"POST",
  url:"new_hpa_fun_aplcval.php",
  data:"aid="+aid,
  success: function(msg){
      if (msg=='OK'){
          dch=1;                    
      }else{
          dch=2;
      }
  }
  });

alert(dch);
AB Shaman
  • 21
  • 12
  • possible 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) – Arun P Johny Oct 12 '13 at 08:31
  • Can you post your php file? Do you observe any console errors using tools like firebug/developer tools? – Vinoth Krishnan Oct 12 '13 at 08:33

1 Answers1

2

By default an AJAX call is asynchronous (that's what the first "A" in AJAX stands for - asynchronous). That means that the success handler will be called SOMETIME LATER. Thus, you can't return the response from the AJAX call from the function like you are trying to do because the value of dch has not yet been set when your function returns.

Instead, you have to restructure your code so that any code that needs the response from the ajax call is either in the success handler or is called from the success handler (and you pass the ajax result to it). You simply can't write simple sequential procedural code with asynchronous ajax calls. You have to learn the new way to structure your code to work with the asynchronous nature of AJAX calls.

var aid='11111111V';
$.ajax({
    type:"POST",
    url:"new_hpa_fun_aplcval.php",
    data:"aid="+aid,
    success: function(msg) {
        var dch = 0;
        if (msg =='OK'){
            dch=1;                    
        } else {
            dch=2;
        }
        // put your code here that uses the result of the AJAX call
        alert(dch);
    }
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979