Try to search your question here, if you can't find : Ask Any Question Now ?

Why is the global variable defined in the function but undefined outside of it?

HomeCategory: stackoverflowWhy is the global variable defined in the function but undefined outside of it?
Avatargaurav asked 5 months ago

I want to set up a system that can show me if my jobs have been completed, paid and so forth.

I have made an API in python’s flask (which works fine) (the front-end is running on flask as well. I’m calling an XMLHTTPrequest on the api to get JSON back. However, inside of the function the global variable “response” is defined but outside of the function it is not.

Maybe i’m just missing something

I have tried different responseTypes, different variable placementt

// Define page variables
var logs = document.getElementById("logs");

// Make global response variable
var response;

// Function for executing GET Requests
function getRequest(adress){

    // Set up new XMLHttpRequest
    var xml = new XMLHttpRequest();"GET", adress, true);

    // Make sure that json is returned
    xml.responseType = "json";

    // Define what happens when a response is received
    xml.onreadystatechange = function(){

        if(this.readyState == 4){

            response = xml.response
            console.log(response) //!OUTPUTS JSON

    // Send the GET Request

//Output all the jobs
console.log(response); //!OUTPUTS undefined

I expect to get a defined variable (response) outside of the onreadystatechange function.

What i get is an undefined variable

1 Answers
Best Answer
AvatarJyoti answered 5 months ago
Your Answer

9 + 8 =

Popular Tags

WP Facebook Auto Publish Powered By :