Changing a global variable via an AJAX call

I seem to be facing a common issue that many others have encountered. Despite my understanding that global variables can be modified inside functions in Javascript, I am struggling with this concept in practice.

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);

After running the code snippet above, I get the following output:

Outside: 0
Inside: 17

While the value displayed inside the function is correct, the one outside of it remains unchanged. What could potentially be causing this discrepancy?

Answer №1

When you call this asynchronous function from outside, it has not finished executing yet. This means that the code after the function call only runs once the operation is complete.

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

However,

console.log("Outside: " + lastMessage);
will continue executing without waiting for the asynchronous function to finish.

If you want to perform an action after getting the value, one approach is to use a callback function like this:

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal approach for verifying the POST request payload

My RESTful API has a POST endpoint for user creation, and I am looking to implement data validation before inserting it into the database. There are two approaches I'm considering: Approach 1: Incorporating model validation in the controller and repe ...

Place the script tags within the window.load function inside the head section

<head> <script type="text/javascript"> $(window).load(function() { // <script src="js/external.js"></script> // }); </script> </head> Is it possible to insert a script tag(< script src="js/exte ...

unable to decode JSON into a structure

After receiving an attribute in JSON format from a REST service and capturing it with an invokeHTTP processor, I am looking to incorporate it into a JSON content flow using the JOLT processor. My existing content looks like this: { "id": 123, "use ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

Steps to remove OTP from dynamodb after a specified time period (2 minutes)

Recently, I have been utilizing the setImmediate Timeout function to call the deleteOTP function with details such as the userId of the OTP to be deleted. However, I am encountering challenges when passing the argument (userId) to the deleteOTP function ...

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

React - optimize performance by preventing unnecessary re-renders of an object property

In my current project, I am working with an auction object that has two properties: remainingTime and amount. To enhance user experience, I integrated a countdown timer using the react-countdown-now library to display the remainingTime. Additionally, there ...

What are the best methods for creating JavaScript charts that efficiently handle massive amounts of data?

After conducting a thorough search, I couldn't find any article similar to what I'm working on for my ASP.Net MVC4 project. The main challenge we're facing is drawing charts with AJAX and JavaScript for extremely large amounts of data. For ...

I am hoping for the outcome to be directed to the homepage

I'm struggling to figure this out, as I am new to classic ASP and JavaScript. I hope someone can help me understand. I want to display the response.write on the main.asp (or the result) page, but each time I try, it redirects to pass.asp on a differen ...

Having trouble with running sudo commands on Hyper in Windows 10?

Working on a Windows 10 system without any VM software, I've installed hyper to utilize node and npm. My laptop has just one account, which is also the local account administrator. Surprisingly, even though I have all the permissions, I am unable to r ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

Troubleshooting problem with AngularJS and jQuery plugin when using links with # navigation

I have integrated a specific jquery plugin into my angularjs single page application. The primary block can be found in the following menu: http://localhost:81/website/#/portfolio This menu contains the following code block: <li> <a href=" ...

Problem encountered while downloading dependencies with Snyk

While attempting to set up the dependencies for the W3C Respec project, I encountered this error message: npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for build steps and `pr ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...