简体   繁体   中英

Javascript declare a global variable within AJAX response

After sending an Ajax post request, I get an array as a response. I want to use this array in another function, I tried to declare the variable before setting its value without putting it in any function.

var their_Info = [];
    $.ajax({
            url: "My PHP url",
            type: "post",
            data: {username:usernames} ,
            success: function (response) {
               their_Info = JSON.parse(response);
            });

If I want to use their_Info in a separate function I am getting undefined..

Below is the php script for reference:

<?php
header('Access-Control-Allow-Origin: *');
$usernames = $_POST['username']; 
//$ids = join("','",$usernames); 
$link = mysqli_connect("localhost", "root", "vKukRKWZRE", "table");
$acc_Info = array();
foreach ($usernames as $value) {
    $query = "SELECT * FROM users WHERE username = '$value'";
    $show = mysqli_query($link, $query) or die("Error");
    while ($row = mysqli_fetch_array($show)) {
        array_push($acc_Info, explode(',', $row['wear']));
    }
}
echo json_encode($acc_Info);
?>

If you try to use their_Info before the AJAX completes, it will obviously return undefined because AJAX is async.

The possible solution

Call your function inside success with the data as an argument. By this, you will be using the response only after the AJAX completes

Despite the comment for proper way of handling callback, you can use window.their_info to set their_info variable in global scope. Not really recommended though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM