AB Shaman
AB Shaman

Reputation: 21

Return data after ajax call success

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);

Upvotes: 0

Views: 1759

Answers (1)

jfriend00
jfriend00

Reputation: 707158

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);
    }
});

Upvotes: 2

Related Questions