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

The webkitTransitionEnd event fires prior to a repaint or reflow occurring

My goal is to create a progressBar that changes its width when an ajax request is made. I want the ajax callback to only execute after the animation of the progressBar is complete. Here is the code I am using: CSS: #progressBar{ position: fixed; ...

A DataTable featuring a contextual menu, the ability to make multiple selections, and the ability

My dataTable is quite complex, with the ability to edit a single row, select multiple rows, and display a context menu for each row. Single row editing and multiple selection are working fine, but the issue arises when trying to open a contextMenu on a rig ...

What causes json.parse to malfunction? and how can you resolve the issue

My server sends data to my JavaScript code in the format below. {"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxxx\"]", "message": "This is a test"}]} To parse this JSON string, my code executes the f ...

Retrieve the unique identifier of the dynamically created button

I have been struggling to retrieve the ID of a dynamically generated button. I attempted to access the specific button ID and utilize it for beforeSend:function(id). However, my efforts were not fruitful. <?php session_start(); require_once "../aut ...

Can you explain the concept of "excluded" in relation to project subdirectories on Webstorm?

When using Webstorm, you have the option to mark project subdirectories as "excluded". However, the full implications of this designation remain unclear in the Webstorm documentation. Does marking a directory as excluded impact debugging or deployment proc ...

Learn the process of dynamically adding new rows and assigning a distinct ng-model to each row

Does anyone know how to create a dynamic table in HTML with unique ng-models for each cell? I've tried the following code, but I'm struggling to figure out how to add ng-model. <!DOCTYPE html> <html> <head> <style> table, ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

Finding the identification of the first element within a nested div using JQuery

Here is the HTML snippet that I am working with: <div id="parent"> <div id="computer"> <div id="items"> <div id="1">hp</div> <div id="2">compaq</div> <div id="3"& ...

Steps for aligning items in a column horizontally in Bootstrap 5

After creating a Grid system with only 2 columns, I placed text in the first column and a carousel in the second. Despite setting a custom size for the carousel image, I'm facing difficulty centering it horizontally within the column. .title-sec { ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Information not displaying correctly on the screen

My latest project is a recipe app called Forkify where I am utilizing JavaScript, npm, Babel, Webpack, and a custom API for data retrieval. API URL Search Example Get Example The app displays recipes with their required ingredients on the screen. Addit ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

The loading of the Bootstrap tagsinput has encountered an error

I am facing an issue with my Django application where tags are not loading properly in an input field using jquery. It seems like the application is unable to locate the bootstrap-tagsinput.css and bootstrap-tagsinput.js files. Can anyone provide guidance ...

When you hover over an image, both the image's opacity and the color of the title beneath it change. However, if the title expands to two lines, it messes up

I am currently working on a project where I have an image and a title displayed below the image. My goal is to change the color of the text when hovering over the image, as well as adjust the opacity of the image. Additionally, when hovering over the title ...

Bootstrap wysiwyg5 editor validation: Ensuring accuracy in your content creation

Currently, I have integrated the Bootstrap wysiwyg5 editor into a form. One of the fields in this form, specifically the text area, is mandatory and cannot be left empty. I am facing a challenge in validating whether the user has entered any content into t ...

Tips for transferring information from an AngularJS application to a Spring controller

Working with AngularJS var app = angular.module('myApp', ['ngResource']); app.controller('UserController', ['$scope', '$resource', '$http',function($scope,$resource,$http) { $scope.deleteR ...

I am having trouble with json_encode in my Symfony2 controller

Just starting out with Symfony2 and AngularJS. Trying to use json_encode to display content from my database, but running into issues. Here's my controller: public function catalogonewAction() { $data = $this->getDoctrine()->getManager() ...

Various issues arising from a single input in Foundation Abide with AngularJS

Trying to set up a form using Foundation has proven challenging, especially when it comes to implementing more advanced error checking. If we take the example of an input field like this: <input pattern="username" required type="text" placeholder="user ...

Displaying empty values in the post via plupload data

I have encountered an issue where a JSON string that I am trying to post is not getting posted, despite being visible in an alert. The strange part is that when I manually create a JSONArray, it gets posted successfully. Below is the code snippet, I would ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...