Daniel Smith
Daniel Smith

Reputation: 43

Modify global variable from ajax request

I know this has been asked countless times, but i can't figure out the problem. As far as i know, you can modify global variables inside functions in javascript. It doesn't work for me.

var lastMessage = 0;
function loadChat() {
$.post("/lastmessage", { roomid: roomId })
    .done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            console.log("Inside: " + lastMessage);
        }
    });
}

console.log("Outside: " + lastMessage);

This gives me

Outside: 0
Inside: 17

The inside value is correct, the outside is not. What could the problem possibly be?

Upvotes: 2

Views: 3440

Answers (1)

enzoborgfrantz
enzoborgfrantz

Reputation: 468

It's asynchronous, therefore when you call it from outside, it has not finished executing yet. What this means is that this part of your code is only reached once the post has completed

.done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            console.log("Inside: " + lastMessage);
        }
    });

but console.log("Outside: " + lastMessage); will continue executing without waiting, since post is asynchronous.

If you want something to happen after you retrieve the value you, one option would be to use a callback function, such as:

function printMessage(message) {
    console.log(message)
}

function loadChat(callback) {
$.post("/lastmessage", { roomid: roomId })
    .done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            callback(lastMessage);
        }
    });
}

loadChat(printMessage);

Upvotes: 4

Related Questions