Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change global variable inside function (JavaScript) [duplicate]

I have a global variable called result and a function, with the purpose of changing the value of result. here's the code I've tried:

checkdate();

function checkdate() {
    //defining startdate,enddate,hotel_id

    $.ajax({
    method: 'GET',
    url: '/checkdate',
    data: {startdate : startdate, enddate : enddate, checkroom : 1, hotel_id : hotel_id},
    success: function(response){
        storeResponse(response);
    }
    });
}

var result = [];
function storeResponse(response) {
    window.result = response;
}
alert(result);

The alert returns nothing, however if I put the alert INSIDE the function, it returns response alright. This seems to be easy but I can't figure it out.

The function is invoked before all this code.

like image 560
HessamSH Avatar asked Mar 15 '26 09:03

HessamSH


1 Answers

There are two things you need to know here:

  1. var result is not same as window.result so use window.result = "Test"; and not the var declaration.
  2. You need to invoke storeResponse() before alert code so that it set the new value and then get that value in alert.

window.result = "Test"; //in global scope
function storeResponse(response) {
    window.result = response;
    console.log(window);
}
storeResponse("Hello");
alert(result);
like image 160
Ankit Agarwal Avatar answered Mar 16 '26 22:03

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!