0

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?

Zvone
  • 165
  • 1
  • 12
  • 2
    $.post is AJAX. AJAX means **Asynchronous** JavaScript And XML. You need to read this: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Sergiu Paraschiv Jun 11 '16 at 13:57

2 Answers2

2

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
   }
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • Yes this could work, but I was wondering if there was a different solution in case I had some code doing something with the text variable after alert-box. Of course I can move that other code too, but I was just wondering. Thanks! :) – Zvone Jun 11 '16 at 14:05
  • OK. I updated the answer for that purpose. – Ali Sheikhpour Jun 11 '16 at 14:08
  • 1
    Or return `$.post` promise and do whatever is needed in a promise callback – charlietfl Jun 11 '16 at 14:11
-2

$.post() is an asynchronous function so alert() is executing before you get data from post() request. Try to use jquery.deferred() to work synchronously

Nafiul Islam
  • 1,220
  • 8
  • 20
  • This is pretty bad advice. The solution is not to force synchronous execution but to learn JavaScript. – Sergiu Paraschiv Jun 11 '16 at 13:58
  • I don't think the OP wants to work synchronously, that would only maintain his misunderstanding of this fundamental property of JavaScript. – samsonthehero Jun 11 '16 at 13:59
  • Also `jQuery.deferred` does not involve synchronicity in any way. It's just a fancier way of writing callbacks. – Sergiu Paraschiv Jun 11 '16 at 14:01
  • Use deferred how? Don't just provide links...provide solution and only use links to support what is contained in the actual answer. This answer has no value to anyone as it is now – charlietfl Jun 11 '16 at 14:07