Zvone Zvone - 5 months ago 14
PHP Question

$.post executes after javascript

sorry if my title is unclear but I'm not sure how exactly to form the question/problem.
So, I have this code:

HTML:

<button onclick="test()">test</button><br>


javascript:

function test(){
var text="Old text";
$.post('test.php',function(data){
text=data;
});
alert(text);
}


PHP:

<?php
echo "New text";
?>


but in the alert box I get "Old text".
How do I fix this?

Answer

Move the alert inside post callback function. Elsewhere the alert is executed while $.post is running yet.

function test(){
  var text="Old text";  
  $.post('test.php',function(data){
      text=data;
      alert(text);
    });

}

Update: if you have more codes to execute after alert, you may wrap those actions inside a new function:

    function test(){
      var text="Old text";  
      $.post('test.php',function(data){
          text=data;
          moreActions(text);
        });
    }

   function moreActions(text){
     alert(text);
     // and more actions to work with TEXT here
   }