The order in which JavaScript is being executed is being reversed

function checkForDuplicate(center, email) {
    $.ajax({
        type: "POST",
        url: "../staff/staffDA.php",
        data: "funId=-4&center=" + center + "&email=" + email,
        success: function (data) {
            if (data.split('|')[0] === 'true') {
                alert('Duplicate Entry Found !!\r\n' + data.split('|')[1]);
                return false;
            }
            return true;
        }
    });
    return true;
}

function processCenterInfo() {
   /* performing necessary steps */

    if (!checkForDuplicate(center, email)) {
        return;
    }

    alert('hello');
    alert('hello');

    /* additional code */
}

Can someone explain why the above functions are being executed in reverse order?

Current sequence of execution is

`hello`
`hello`
`Duplicate Entry Found !!`

The expected execution should only be Duplicate Entry Found !!, and it should exit the function.

Answer №1

duplicateCenter function includes AJAX code which operates Asynchronously

I need assistance in understanding why the above function is executing in reverse order? The code is functioning correctly in an asynchronous manner

For further information on AJAX, please check out this answer:
How do I return the response from an asynchronous call?

Possible Solution: Utilize callback functions

function duplicateCenter(center, email, callback) {
  $.ajax({
    type: "POST",
    url: "../staff/staffDA.php",
    data: "funId=-4&center=" + center + "&email=" + email,
    success: function(data) {
      var flag=false;
      if (data.split('|')[0] === 'true') {
        flag=true;
        alert('Duplicate Entry Found !!\r\n' + data.split('|')[1]);
      }
      if(typeof callback==='function') callback(flag);
    }
  });
}

function addCenterInfo() {
  /* some coding and initializations */
  duplicateCenter(center, email, function(isDuplicate) {
    if (isDuplicate) {
      alert('duplicate');
    } else {
      alert('not duplicate');
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

It's important to note that in the term "Ajax," the letter "A" represents "Asynchronous." One thing to consider is that you are initiating the duplicateCenter() function prior to the alerts, however, this function ends without pausing for a response. Consequently, once the call to staffDA.php finishes, the alerts have already been triggered.

Answer №3

When making AJAX calls, it is important to remember that they are asynchronous. This means that you cannot predict exactly when the call will return. To handle this unpredictability, a success function must be specified. This function only executes once the AJAX call has returned, which could happen in mere seconds or take longer.

To ensure that your code runs only after the success method has finished its execution, follow this structure:

function duplicateCenter(center, email) {
    $.ajax({
        type: "POST",
        url: "../staff/staffDA.php",
        data: "funId=-4&center=" + center + "&email=" + email,
        success: function (data) {
            if (data.split('|')[0] === 'true') {
                alert('Duplicate Entry Found !!\r\n' + data.split('|')[1]);
                itWasFalse();
            }
        }
    });
}

function itWasFalse() {
   // just an empty return? How lonely (and unnecessary - all JS functions return)
}

function moreCodes() {
    alert('hi');
    alert('hi');

    /* additional codes */
}

function addCenterInfo() {
   /* execute some coding and initializations */
   duplicateCenter(center, email);
}

Answer №4

The sequence in which function declarations are executed can vary depending on how they are invoked.

Answer №5

I made a small tweak in my function by adding an extra line of code:

async:false

With this change, the function now behaves exactly as I had anticipated.

function checkDuplicate(center, email) {
flag=true;
    $.ajax({
        type: "POST",
        url: "../staff/staffDA.php",
        async:false,
        data: "funId=-4&center=" + center + "&email=" + email,
        success: function (data) {
            if (data.split('|')[0] === 'true') {
                alert('Duplicate Entry Found !!\r\n' + data.split('|')[1]);
                flag=false;
            }else{
               flag=true;
            }

        }
    });
    return flag;
}

For more information, visit:

jQuery: Performing synchronous AJAX requests

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

I'm puzzled as to why, but my code seems to be causing an issue with the command prompt, possibly due

Recently, I've been taking on the challenges of Advent of Code. Day 2 has me stumped, as there's a peculiar issue with the code when running it through node.js in the command prompt: const fs = require("fs"); var valid = fs.readFileSync("inpu ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...

Load a webpage using javascript while verifying permissions with custom headers

Seeking guidance as a novice in the world of JavaScript and web programming. My current project involves creating a configuration web page for a product using node.js, with express serving as the backend and a combination of HTML, CSS, and JavaScript for t ...

The cannon-es program experiences crashes every time two Convex polyhedrons collide with each other

Currently, I'm working on implementing a dice roller using three.js and cannon-es. Everything runs smoothly when there's only one dice, rolling against the ground plane in a satisfactory manner. However, the trouble arises when I add a second di ...

Sleek transition-ready zoom functionality for THREE JS with clickable controls

Hey there, I've been attempting to animate a transition between scenes in THREE js for quite some time now. I have successfully cleared the scene and recreated the next one, but the transition between them is proving to be quite challenging. I have cr ...

Continuous scrolling feature for dynamically loaded content via ajax requests

Currently, I am performing a WP_Query on page-a.php. This specific page contains a div named target where the content of page-b.php is loaded into. Page-a represents a custom template while page-b is an archive page. The layout structure on page A can be ...

What is the best method for linking two ajax requests together?

Here is the code snippet I'm currently working with: <script> $(function () { $('#AdminCreateNewUserSubmit').on('click',function(){ $("#admincreatenewuserform").ajaxForm( { target: '# ...

JavaScript personalized video controls. Silence the video by manipulating the input range element

As a newcomer to javascript, I am working on creating custom video controls using js. One issue I am facing is with a span element that contains a mute/unmute icon. When I hover over this span element, a child element appears with an input range bar for ad ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

``I'm having trouble getting the onchange event to function properly in a customized

After following a tutorial, I successfully created a custom select dropdown using the provided link. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select However, I am facing an issue with the onchange event not working for the select ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

What is the process of invoking a secondary "external" function with Nodejs, Expressjs, and bluebird?

Struggling with creating a nodejs application, a new area for me. I've managed to work with Promises and fetch data from a database. Take a look at the code below: myModel.js var express = require('express'); var app = express(); var Promi ...

Animating object properties instead of static values

I am faced with a challenge of dealing with a large array of objects, all having the same structure: { title: 'Text', value: 'Text'} My goal is to loop through this array using a map function and display only two objects at a time. Th ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

Navigating through states in AngularJS

My application has three states: app, app.devices, and app.devices.device. While the first two states are functioning properly, the app.devices.device state is not working as expected. Here is the code for reference: http://pastebin.com/r1kYuExp http://pa ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Guide on updating the form structure with ajax

Lately, I've been working on a contact module with 3 columns: name, email, and phone. There's also a +1 button that adds a new row to input another contact using ajax. However, a problem arises when updating the structure as the data in the old c ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

Having trouble retrieving a value within the jQuery.ajax success function

I need to implement jQuery Validator in order to validate if a user's desired username is available during the sign-up process. The PHP script untaken.php is responsible for checking this, returning either ok if the username is free or taken if it is ...