JavaScript function to evaluate true conditions

I am encountering an issue while calling sub functions connected to if statements within my main function. Even though the sub functions are supposed to return true or false, the expected alerts are not appearing.

   if (functionAAA()){
       alert("111111111");

       if (functionBBB()){
                      alert("2222222");

           if (functionCCC()){
                          alert("333333333333");

           }            
       }
   }

The functions functionAAA, functionBBB, and functionCCC are expected to return true, triggering alerts accordingly. However, this behavior is not happening as anticipated. What could be going wrong in my implementation?

I suspect that the issue lies within the function side itself. The definition of functionAAA is provided below:

function functionAAA(){
    var indexId = 1;

    var dataItem = datasourceAppList.at(indexId);
    var deviceKey = localStorage.getItem('LsDeviceKey');
    var baseUrl = localStorage.getItem('LsBaseUrl');    
    var errorMessageInfoText;
    var status;

    $.ajax({

        url: baseUrl + '/test/cloud/FE/1.0/test.php',
        data: {
            PAR1: dataItem.par1,
            PAR2: dataItem.par2,
            PAR3: deviceKey,
            PAR4: dataItem.par3,
            PAR5: "5664456"
        },
        type: 'GET',
        crossDomain: true,
        dataType: 'jsonp',
        error: function () {
            showErrorDialog("Key Validation Failure");
        }

    }).done(function (data) {

        $.each(data, function (k, v) {

           // alert("k  " + k + "  v  " + v);
            if (k == 'STATUS') {
                status = v;
            } else if (k == 'ERROR_MESSAGE') {

                errorMessageInfoText = v;
            }
        });

        if (status == 'TRUE') {
            alert("ok");
            return true;

        } else {
            return false;
        };

    });    

}

The other functions mentioned directly return true without any issues.

Additionally, it's worth noting that I do receive the "ok" alert within the function when necessary.

Answer №1

Your code needs restructuring to handle asynchronous AJAX calls properly. The anonymous function inside .done() is executed after functionAAA has already completed and returned undefined, as AJAX calls are asynchronous by nature.

To address this issue, you can utilize the promise returned by $.ajax and use .then():

function functionAAA(){
    return $.ajax({
        url: 'http://jsfiddle.net/echo/jsonp/',
        dataType: 'jsonp',
    });
}

functionAAA().then(function() {
    alert("111111111");
    if (functionBBB()){
        alert("2222222");
        if (functionCCC()){
            alert("333333333333");
        }            
    }
});

To see it in action, check out the demonstration on JSFiddle.

Answer №2

The outcome of your function is blank. Executing an asynchronous request and returning the response are incompatible — this defines the essence of asynchronicity. To execute additional tasks after the ajax call finishes, assign a callback to the function and invoke it instead of trying to return from the ajax handler.

Answer №3

I've had success with the following script. Could you share your implementation of functionAA, BB, etc?

    <script>
    function functionAA() {
        return true;
    }
    if(functionAA()){
       alert("hello");
    }
    </script>

Answer №4

For improved efficiency, include the following code snippet in your script to ensure that your ajax call is synchronous and waits for the response before proceeding with further actions. This will allow you to verify the response and return a boolean value based on the outcome. As it stands, the current setup does not return any data.

async: false

Answer №5

give it a shot...

 if (functionAAA()){
           alert("Testing 1,2,3");

           if (functionBBB()){
                          alert("Ready or not, here I come!");

              else if (functionCCC()){
                              alert("Houston, we have a problem.");

               }            
           }
       }

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

Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below. Thank you. On a JSP page, there is a list ...

What is the best way to include several IDs in a discord.js verification process?

I am attempting to create a basic script that verifies if the user's ID matches the one specified in the code. However, I'm struggling to understand how to achieve this. Any assistance from you all would be greatly appreciated. if(message.autho ...

Tips for updating and triggering useEffect when the router changes in React JS

I have a ChartPage function that is being called three times within three different routers. Inside the ChartPage function, I am using "useEffect" to update some variables based on the selected route. However, for some reason, it only triggers once, and wh ...

Is there a reason why the Chrome browser doesn't trigger a popstate event when using the back

JavaScript: $(document).ready(function() { window.history.replaceState({some JSON}, "tittle", aHref); $(window).bind("popstate", function(){ alert("hello~"); }); }); Upon the initial loading of the www.example.com page, the above JavaScript code is ex ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

Error: Unable to access the 'offsetTop' property of null

I attempted to implement a scroll effect in my project. The goal was for users to be taken to a specific section when they clicked on an option in the navbar. However, I encountered an error during implementation. Below is the code snippet where the error ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look: const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce']; let imageObjects = [ { ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

HTML - Using Tables to Add and Edit Rows

Take a look at this demo on JSFiddle for my project: Demo jsfiddle I'm currently in the process of creating a table with various functionalities. The function "sortTable" is responsible for sorting the table and it's functioning as expected. T ...

Can one access the method definition within a Visual Studio Code setup for an AngularJS project?

I'm on a quest to locate the method definition within my AngularJS project, but alas, I am struggling to discover a quick and easy shortcut for this task. My attempts with Ctrl + Click only led me to the initial occurrence of the variable's decla ...

Retrieving the ID and value of a specific dropdown list using jQuery from an array of dropdown lists

My HTML structure looks like this: <?php foreach($active_brand as $brand) { ?> <select name="selector" id="selector"> <?php foreach($options as $option) { ?> <option <?php if($brand['State'] == $option) { ?& ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

Generate a hyperlink that directs to a page and triggers the expansion of an accordion section

I am currently working with a Bootstrap 5 accordion component: <div class="accordion" id="accordionIndexPage"> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingOne& ...

Tips for successfully incorporating PHP dynamic parameters separated by commas into a JavaScript onclick function

How can I pass PHP dynamic parameters separated by commas to a JavaScript onclick function? Can someone assist me with the correct solution? The code below is not working as expected. echo "<td><a href='#' onclick='editUser(". $row ...

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...