0

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);
?>
charles M
  • 75
  • 1
  • 7
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Sep 15 '16 at 17:16
  • you have a missing closing parenthesis in your first code – NotGI Sep 15 '16 at 17:16
  • Where (and when) are you trying to access `their_Info`? – gen_Eric Sep 15 '16 at 17:18
  • 1
    Also, ***please*** use prepared statements for this. You wouldn't want me to try to login as `'; DROP TABLE users; -- `, would ya? – gen_Eric Sep 15 '16 at 17:19
  • Ok after reading the possible duplicate I am thinking of calling the functions that uses the variable right after changing their_Info value in the response. – charles M Sep 15 '16 at 17:19

2 Answers2

0

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

Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
0

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.

YSJ
  • 382
  • 2
  • 14