Purpose of triggering another function during an ajax request

I have encountered an issue while working on a project. There is a page with an input field called balance within a div named balanceDiv. This field should not be visible to the admin, so I used ng-show to hide/show the div based on the user's login ID. I wrote two functions in the Angular controller - one for retrieving the login ID and another for showing or hiding the div based on that ID. The condition is that if the login ID is 1 (admin), the div will be hidden; otherwise, it will be shown.

        init();
        function init()
        {
            setLoginId();
            showHide();
            initialize();
        }

Initially, the setLoginId function is supposed to execute first followed by showHide function. However, what I observed was that the execution jumps to the showHide function when making an AJAX call.

    function setLoginId()
    {
        var apiRoute = baseUrl + '/api/AmountDists/GetLoginId/';
        var result = CrudService.getAll(apiRoute);
        result.then(function (response) {
            debugger
            $scope.loginId = response.data;
        },
        function (error) {
            console.log("Error: " + error);
        });
    }
    
    function showHide() {
        if ($scope.loginId == 1) {
            $scope.balanceDiv = false;
        }
        else {
            $scope.balanceDiv = true;
        }
    }

After calling the AJAX in setLoginId, the execution moves to showHide before the response is received, causing $scope.loginId to be undefined. Why is this happening? Why does the execution switch to another method during the AJAX call?

Answer №1

In order for the functions to be connected:

    initialize();
    function initialize()
    {
        setLoginId().then(function(data) { 
            showOrHide(data);
        }).then(function () {
            init();
        });
    }

Make sure to return the promise for linking them:

function setLoginId()
{
    var apiRoute = baseUrl + '/api/AmountDists/GetLoginId/';
    var promise = CrudService.getAll(apiRoute);
    return promise.then(function (response) {
  //^^^^^^  return derived promise
        debugger
        $scope.loginId = response.data;
        //RETURN data to chain
        return response.data;
    },
    function (error) {
        console.log("Error: " + error);
    });
}

Include loginID as a parameter:

function showOrHide(loginID) {
    if (loginID == 1) {
        $scope.balanceDiv = false;
    }
    else {
        $scope.balanceDiv = true;
    }
}

By returning the promise, and using the .then method of the promise, the second function will only execute after the completion of the first XHR.


I am curious about the reason behind this

It is crucial to understand that the $http service promptly returns an unresolved promise and simultaneously initiates an asynchronous xmlHttpRequest (XHR) . The promise is later fulfilled (resolved or rejected) upon receiving results from the server.

The code following an asynchronous API call is executed right away. If there is a need to delay code execution until the XHR completes, it must be provided as a function to the .then method of the promise.

For further insight, refer to:

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

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

Facing issues while attempting to retrieve the generated PDF through an Ajax-triggered controller action

I am having trouble downloading a PDF/XLSX file from the controller. I have tried using both jQuery and Ajax, but I can't seem to get it to work. Here is an example of the code in the controller: var filestream = new FileStream(pdfoutputpath + " ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

What is the best way to implement Media Queries in the Next.js application Router?

I am currently working with Next.js 13 and the App Router. Within my client component, I have implemented media queries in JavaScript to customize sidebar display for small and large screens. "use client"; export default function Feed() { co ...

Angular: Leveraging Nested Callbacks for Efficient HTTP Queries

I'm currently facing an issue with structured English. GET HTTP Resource FOR every data item received do GET another HTTP Resource Alter the original data from the outer loop with data from the inner GET RETURN altered data How can ...

What is the best way to incorporate Javascript into jQuery tabs?

On my website, I have implemented a Jquery and CSS tab system similar to the one found here. Each tab contains a Facebook feed box, a Twitter widget, and a ranking widget for my blog. However, when these widgets are placed within the tab content area, they ...

Maintaining Object Position in 2D Transforms

I am trying to create multiple perspective-transformed rectangles in the lower right corner of a canvas by using ctx.transform: ctx.transform(1, 0, -1, 1, 10, 10). My goal now is to adjust the size of the drawing based on a variable scale=n, while keeping ...

Retrieve the value of a nested JSON object using the name of an HTML form field, without the use of eval

I am facing a similar issue to Convert an HTML form field to a JSON object with inner objects, but in the opposite direction. Here is the JSON Object response received from the server: { company : "ACME, INC.", contact : { firstname : "Da ...

Slider that allows range selection after midday

Currently facing a dilemma using the noUiSlider plugin. I have set up a time range picker starting from 6 am to 6 am the following day. Everything works smoothly until it reaches 23:59, but I need it to display 1:00, 2:00 instead of 25:00, 26:00 for the ...

Exploring the realm of Angular templating and routing combined with the power

Currently, I am in the process of developing my very first Angular website that involves templating and routing. My goal is to have an image on the page that spans the entire window size minus 70 pixels. //Using Jquery (This particular section functions ...

Encountered an error: "switch/mergeAll/flatten is not a valid function" when working with the http driver

As I delve into learning CycleJS, one thing that has caught my attention is the usage of Cycle's HTTP Driver. It seems that in order to reach the stream level, merging the response stream stream with RxJS switch/mergeAll is essential. However, when at ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

Unable to scroll when utilizing ng-html-bind functionality

My device specifications: $ ionic info Your system details: Cordova CLI: 6.2.0 Gulp version: CLI version 3.9.1 Gulp local: Ionic Framework Version: 1.2.4 Ionic CLI Version: 2.0.0 Ionic App Lib Version: 2.0.0-beta.20 OS: Distributor ID: LinuxMint Desc ...

Loss of styling is observed with jQuery's html() function

Here is the HTML code I am working with: <div class="myList"> <select> <option value="1">Item1</option> <option value="2">Item2</option> </select> </div> Everything looks great in terms of CS ...

Tips for setting a jQuery variable equal to the value of a JSON object

When I try to assign courseid and batchid as defaults using defaultValue => defaultValue: courseid and defaultValue: batchid, the values are not being saved correctly in my database. $(document).ready(function() { var courseid = null; var bat ...

<use> - SVG: Circles with different stroke properties

Why is the stroke of both <use> elements being ignored here? The stroke color of <circle> is set to blue, which is also appearing on both <use> elements. Why? I am trying to set different stroke colors for all three of these elements, bu ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...