retrieve the value of the 'show' variable before displaying it

Trying to figure out the logic behind a question but coming up empty. In my JavaScript app using OOP, I'm attempting to assign a function as a variable value.

Initially, the value of init_s.__temp_var is an empty object. When the function logic_s.get_active_statuses(..) is called, it should overwrite this value. However, that's not happening. Here's what's going on:

var widget = {
    settings: {
        __temp_var: {}
    },

    init: function () {
        init_s = this.settings;
        logic_s = this.functions_available;
    },

    functions_available: {
        get_active_statuses: function (id) {
            jQuery.ajax({
            url: .....,
            type: 'POST',
            dataType: 'JSON',
            data: {
                ....
            },
            success: function (data) {
                init_s.__temp_var = data; // not working
                return data; // undefined
            },
            error: function (e) {
                console.log(e.message);
            }
        });
        }
    },

    my_actions: {
        logic: function () {
            var active_services_status = logic_s.get_active_statuses(5);
            console.log(init_s.__temp_var); // should print {id : 5}
            console.log(active_services_status ); // if used with return prints "undefined"
        }
    }
};

When I call logic_s.get_active_statuses(5); for the first time, it logs an empty object. Then, when called for the second time, it logs {id : 5}. This pattern continues, with the returned value increasing by increments of 5 every fourth call. Why is this behavior occurring? It appears that the variable is being set after it is printed.

EDIT:

the current behavior causing the "undefined" return:

function get_active_status (id) {
                jQuery.ajax({
                url: .....,
                type: 'POST',
                dataType: 'JSON',
                data: {
                    ....
                },
                success: function (data) {
                    return data; // undefined
                },
                error: function (e) {
                    console.log(e.message);
                }
            });
            };

get_active_status(5); // returns "undefined" instead of the sent object

Answer №1

When utilizing AJAX, your requests are asynchronous. This means that it sends a request here.

logic_s.get_active_statuses(5)

It does not wait for the response (success only executes after receiving a response from the server) and continues to run.

console.log(init_s.__temp_var); // should output {id : 5}
console.log(active_services_status ); // when used with return, outputs "undefined"

You can use setTimeout(), but this eliminates any aspect of asynchronous behavior. Another option is to utilize the async setting, which is true by default. Your function would look like this:

function get_active_status (id) {
            jQuery.ajax({
            url: .....,
            type: 'POST',
            dataType: 'JSON',
            async: false,
            data: {
                ....
            },
            success: function (data) {
                return data; // outputs undefined
            },
            error: function (e) {
                console.log(e.message);
            }
        });
        };

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

Element Proxy

I decided to experiment and see how a library interacts with a video element that I pass to it. So, I tried the following code: const videoElement = new Proxy(document.querySelector('video'), { get(target, key) { const name = typeof ...

"Hey, getting an error stating 'require is not defined' while attempting to configure the .env file. Need some help here

I am currently working on setting up a .env file to securely store the credentials for my Firebase database within a vanilla JavaScript project. Despite following various tutorials and referencing the documentation for dotenv, I continue to encounter an er ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

What is the method for retrieving the dropdown ID from a sumo select dropdown?

I am facing an issue with retrieving the dropdown ID from a Sumo Select dropdown that has a dynamically changing ID. There are multiple dropdowns available on the page. Below is a snippet of the code: <div id="shareOnFriendsList" > <sel ...

An unexpected error has occurred in Discord.js: ReferenceError - DiscordCollection is not recognized

While working on my Discord bot using Discord.js and following Codelyon's code, I encountered an error that has me stuck: ReferenceError: DiscordCollection is not defined at Object.<anonymous> const {Client, Intents, DiscordAPIError, Collection} ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Struggling to generate components using JQuery

I'm currently working on a form that checks the availability of a username using jQuery. Here is the initial form code: <form> <input id="checkuser" type="text" name="user" placeholder="Your username"/> </form> Below is the jQuer ...

Experiencing an error message of "undefined" when attempting to retrieve a value from outside

While working with Node.js, I utilized a request to fetch some data from an API. However, when I attempted to access these values outside of the function braces, they returned undefined. var tab_det; request.post({url:'https://ludochallenge.com/i ...

Understanding the intricacies of JavaScript function calls often results in unexpected null returns

I currently have a code that is able to run and collect data using an AJAX library. My goal is to allow users to add their own functions to the library and execute them, similar to $.get. It may be a bit difficult to fully explain what I am trying to achie ...

The multi-level navigation bar is not displaying properly

I am currently facing an issue with my Mega menu. It displays two levels of menus perfectly fine, but I need to add a third level as shown in the image below. However, when I try to include the third level, it disrupts the design and causes the Grand Child ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

Dealing with the state of an array of checkboxes: What you need to know

Is there a way to individually control the checked state of an array of checkboxes? Here is the array in question: const CheckboxItems = t => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', ...

Issues with implementing Callouts CSS in Highcharts are causing complications

Currently, I am attempting to construct a callout, and I aim to format the callouts using CSS. Unfortunately, the CSS implementation seems to be malfunctioning for some unknown reason. Below is the HTML: <script src="https://code.highcharts.com/highch ...

After the geolocation is retrieved, employing a callback function

I have been developing a web service program that tracks the location of users using geolocation. The program initiates geolocation to locate the user and then proceeds to record the location. However, since geolocation relies on a callback function to ret ...

Trouble connecting to MySQL database using Sequelize in Node.js

I am delving into Node.js and attempting to establish a connection with Sequelize by following the guidelines provided in its documentation (). Below is my db.js file: const Sequelize = require('sequelize') const db = new Sequelize('chat&a ...

What is the process for converting an array of strings into a 2D array?

How can I transform the string ["0,1", "0,1", "1,2"] into an array of arrays like this: [[0,1], [0,1], [1,2]]? ...

Tips on aligning three divs horizontally within a container while maintaining a height of 100%

UPDATE: The alignment has been corrected by adding floats. However, the height still doesn't fill 100%. Check out the new look: Image Link In my footer container, I want to arrange 3 columns (colored green, white, and red for clarity). Currently, the ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

Solution for unresolvable Ajax token error

I am encountering an error after using setTimeout and receiving an unexpected token. I was attempting to handle errors in my ajax request by displaying a message if there is one, or reloading the webpage after a few seconds. function submit ...