Waiting for $ .post to complete

It looks like my script doesn't want to wait for the $ .post call to complete. This is problem. Here are a few pseudo codes:

<script type="text/javascript" language="javascript">
$(document).ready(function(){
  // Global var, to be used everywhere in the ready scope 
  // Note its default value!    
  var test = false;
  $.post('test.php',{},function(result){
   if(result=='yes')
   {
    // This gets executed!
    alert('Its true! Hurraaay!');
    test = true;
   }
   else
   {
    test = false;
   }
  }

  if(test==false)
  {
   // THIS gets executed, despite the fact that we set test to true!
   alert('Awww....');
  }
  // it reaches this, showing us that there was no error!
  alert('Im alive!!!');
  // and a whoooole bunch of other code here...
}
</script>

What is the best way to make sure my email call is complete before continuing without hanging the browser? Hope for something that is not too dirty. :)

+2
source share
5 answers

Not too messy to use callbacks properly.

Just create a function outside the call .post()and call it inside .post()if you think this is appropriate. You make a lot of callbacks and use them inside AJAX calls in a very flexible way.

, alert(), - alert() .post(). , .

JavaScript . .

+4
<script type="text/javascript" language="javascript">
$(document).ready(function(){
  // Global var, to be used everywhere in the ready scope 
  // Note its default value!    
  var test = false;
  $.post('test.php',{},function(result){
   if(result=='yes')
   {
    // This gets executed!
    alert('Its true! Hurraaay!');
    test = true;
  // it reaches this, showing us that there was no error!
  alert('Im alive!!!');
  // and a whoooole bunch of other code here...

   }
   else
   {
    test = false;
   // THIS gets executed, despite the fact that we set test to true!
   alert('Awww....');

   }
  }
}
</script>
+2

? , .

var test = false; // NOW it global

// Just so we can use the method again
function postSomething() {
  $.post('test.php', {}, function(result) {
    if(result === 'yes') {
      alert('Its true! Hurraaay!');
      test = true;
      alert('Im alive!!!');
    } else {
      test = false;
      alert('Awww....');
    }
  });
}

$(document).ready(function() {
  postSomething();
});

, .

0

JQuery.post() script. , script.

, , . , .

$(function() {
    postTest();
});

function postTest() {
    $.post(
        'test.php',
        {},
        function(response) {
            if(response == 'yes') {
                testSuccess();
            } else {
                testFailure();
            }
        }
    ); 
}

function testSuccess() {
    alert("Success");
}

function testFailure() {
    alert("Failure");
}
0
source

All Articles