Use variable outside the success function from an ajax/jquery call

Solution 1:

 var test; // <-- (1) This code runs first  
 $.ajax({  // <-- (2) Then this runs  
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg); //<-- (4) Finally this is run. IF your request is a success 
        test = msg; 
    },
 });
 Validate.fail(test); // <-- (3) This runs third  

Look at the order in which the code runs. Your variable is simply not available at that point because it's running when the code is triggered via the callback

Solution 2:

Probably because Validate.fail(test) occurs immediately after the asynchronous call. Remember it is ASYNCHRONOUS, meaning it executes parallel to javascript running on your page.

Solution 3:

enter code here var test;
 $.ajax({
    type: "GET",
    async: false,
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});
Validate.fail(test);

//Make your ajax function synchronous, set the json parameter "async: false", so javascript has to wait until test is assigned a value.

Solution 4:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var xm;

  $("#txt").ajaxComplete(function(){
    $('#txt').html(xm);
  });

  $("button").click(function(){

    $.ajax({
      url: 'DBresult_load.php',
      dataType: 'html',
      data: { },                 //you can pass values here
      success: function(result) {xm =result;}
    });
  });


});
</script>
</head>
<body>

<div id="txt"><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>

Here is the solution for passing values to variable from Ajax request. Hope this helps.