Arcadier / Developer-Community-Support

:revolving_hearts: Share new ideas with us and report bugs/problems here
4 stars 1 forks source link

Problem with assigning values to variables inside ajax #9

Closed naseer2426 closed 3 years ago

naseer2426 commented 5 years ago

Your issue/question: I am not able to assign a variable inside the .done function of my ajax call.

What you expect to achieve I need it to assign the value of response to a variable so that i can use it later.

What happens instead The value of the variable becomes null when I call it outside the .done function.

Screenshots The code I wrote

function getCookie(name){
  var value = '; ' + document.cookie;
  var parts = value.split('; ' + name + '=');
  if (parts.length === 2) {
      return parts.pop().split(';').shift();
  }
}

var baseURL = window.location.hostname;
var token = getCookie('webapitoken');
var allUsers;

$(document).ready(function(){
  allUsers = getAllUsers();
})

function getAllUsers()
{
  var allusers;
  var admin = document.getElementById("userGuid").value;

  var settings = {
    "url": "https://"+baseURL+"/api/v2/admins/"+admin+"/users",
    "method": "GET",
    "headers":{
      "Authorization": "Bearer "+token
    }
  };

  $.ajax(settings).done(function(response){
    allusers = response["Records"];
    console.log(allusers);
  });

  console.log(allusers);
  return allusers;
}

Line 37 is the console.log outside the .done function and line 34 is the console.log inside the .done function.

ajaxConsole

Your system/software details Windows 10 using Google Chrome

ABHINAV112 commented 5 years ago

So, the problem you are running into is that AJAX is asynchronous. Therefore, the code inside the AJAX will only run after the rest of the code executes. To make your code run synchronously, add the following attribute into your settings JSON.

"async": false
naseer2426 commented 5 years ago

Thank you that worked. I changed my settings to:

 var settings = {
    "url": "https://"+baseURL+"/api/v2/admins/"+admin+"/users",
    "method": "GET",
    "headers":{
      "Authorization": "Bearer "+token
    },
    "async":false
  };

ajaxSolved