0

I want to change var code value to "asd" if data output is true but it is not working.

current result

enter image description here

jquery code :

$('.generate').click(function() {
      var code = "vhe8t";

      $.post('functions/functions.php', {
        fun: "code_generate",
        string: code
      }, function(data) {
        if (data == "true") {
          code = "asd";
          console.log("hello world");
        }
      })

     console.log(code);
});

Function.php code

<?php

  $connection = new mysqli("localhost", "root", "root", "shop_management");

  $fun = "";
  if (isset($_POST['fun'])) {
    $fun = $_POST['fun'];
  }

  if ($fun == "code_generate") {
    $code = $_POST['string'];
    $query = "SELECT * FROM code WHERE code='$code'";
    $run = mysqli_query($connection, $query);
    $nums = mysqli_num_rows($run);

    if ($nums > 0) {
      echo 'true';
    } else {
      echo 'false';
    }
  }
?>
saqib kifayat
  • 136
  • 2
  • 14
  • 2
    Async problem! this is duplicated for sure. – Ele Mar 24 '18 at 19:18
  • The `console.log()` is being executed before the `$.post()` has complete as **Ele** has pointed out *"Async problem"*. If you can to update the `code` variable then you should define it in the global scope. – NewToJS Mar 24 '18 at 19:20

1 Answers1

3

$.post runs asynchronously. When that function is run, it only sends out the request - the response hasn't come back yet, so when you run console.log(code);, code still hasn't changed during that 1ms.

Put it in the callback instead:

$.post('functions/functions.php', {
  fun: "code_generate",
  string: code
}, function(data) {
  if (data == "true") {
    code = "asd";
    console.log("hello world");
    console.log(code);
  }
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320