What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not.

I have noticed that the flag_stop_fax variable remains set at zero, even when there is a response text present (e.g., "A fax has already been sent.").

flag_stop_fax = 0;
xmlhttp.onreadystatechange=function() 
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    {
        var response = xmlhttp.responseText;
        if (response!='')
        {
            flag_stop_fax = 1;
            alert(response);
        }
    }
}

xmlhttp.open('GET','/check_for_active_fax.php?fax_number=' + fax_number + '&t='+Math.random(),true);
xmlhttp.send();

alert(flag_stop_fax); // displays "0" even with non-empty response from xmlhttp.responseText

There are additional validation components associated with this issue, but the provided script should help highlight the underlying problem. The 't' variable serves as an anti-caching measure and isn't utilized for any specific purpose.

Hence, why is the flag_stop_fax variable failing to be assigned a value of 1?

Answer №1

To grasp AJAX, you need to understand its asynchronous nature. When you trigger xmlhttp.send();, your request is sent and the code keeps running. This means that the next line that gets executed is:

alert(flag_stop_fax);

At this point, flag_stop_fax is still at zero because the request hasn't finished yet.

The callback function specified for xmlhttp.onreadystatechange will only be run once the request is complete. The flow of execution is not linear in this case. It goes something like this:

  1. xmlhttp.send(); - request initiated
  2. alert(flag_stop_fax); - variable flagged

    ...
    ...
    (some time later, when server responds)

    xmlhttp.onreadystatechange kicks in, changing the value of flag_stop_fax.

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

Saving a picture to local storage with the file input type in ReactJS

I am attempting to save an image in the browser storage once a user selects an image from their computer. <div className="add_grp_image_div margin_bottom"> <img src={img_upload} className="add_grp_image"/> <input type="file" class ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Enhance your app with the seamless navigation experience using Ionic 2

As a beginner in Angular2, Ionic2, NodeJS ... I am experimenting with writing some code to learn. In my journey, I attempted to create a screen with 3 tabs and a menuToggle. When the application is launched, clicking the menuToggle button on the first tab ...

Creating a code script for the purpose of automating npm commands

Currently, I am immersed in an angular js project and I have a desire to streamline the execution of the following two commands. ./node_modules/protractor/bin/webdriver-manager update ./node_modules/protractor/bin/webdriver-manager start The challenge li ...

Pass additional parameter while calling a function in Vue

Visit Element on GitHub Check out the upload component <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :on-error="handleUrlError" :on-success="handleUrlSuccess"> <i v-else class="el-icon-plus avatar-uploade ...

Exploring JSON Arrays with Visualization through Google Charts

I'm facing a challenge with displaying a multi-series chart using a JSON feed containing two arrays. I can't seem to figure out how to make it work and I feel stuck. { "Protein": [{ "Count": 2, "Day": "Friday", "Type": "Protein" }, { ...

Enhance LCP Performance in Next.js for Faster Loading Speeds

I'm currently working on a next.js project (version 11.1.2) and my goal is to improve the page speed performance. To track this, I am using Google PageSpeed Insight for evaluation. Presently, the scores stand at: 40-50 for mobile (!!) 80-90 for deskt ...

Exploring the functionalities of jQuery within ajax-loaded content

My web page consists of the following code: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>test</title> <script src="jquery-2.1.1.min.js"></script& ...

Unable to retrieve the unique identifier for this item

When attempting to retrieve the current ID of an item in a table by clicking the Purchase button and using console.dir, it only displays the first element. I have also tried console.dir for this.id but it returns nothing. function listProducts() { ...

insert a new field into the database within Prisma while ensuring existing table data remains untouched

I have been working with the Prisma ORM and I currently have some data in my table. This is how my model looks: model User { id Int @default(autoincrement()) @id username String @db.VarChar(100) @unique } model Post { id Int @id @defa ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

Encountering difficulties in applying a dynamic aria-label to the md-datepicker component

I am currently utilizing the md-datepicker feature in my project. You can check out how it works here: https://material.angularjs.org/latest/demo/datepicker However, I am facing an issue where I am unable to dynamically add a value to the aria-label attri ...

Challenges encountered while incorporating a method in a subclass

I've encountered a bit of an issue... the situation is that I have a base class that contains implementation for all GET/POST/PUT/DELETE operations and it's a Generic class, so essentially any Entity I update passes through there. Additionally, I ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Issues with rendering AngularJS onto an HTML page are currently being experienced

I was attempting to learn AngularJs in order to improve my front-end development skills, but unfortunately I ran into some issues. Despite following the video tutorials on their site step by step, I couldn't get it to render correctly. Here's the ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

Iterating over the IDs of div elements using jQuery loop

Currently, I am working with a bootstrap accordion and attempting to retrieve the ID and HREF values for each individual accordion using jQuery. Here is the code snippet that I have been utilizing: $('.room-loop').each(function(id){ $('. ...

Navigating to my own posts within Nuxt: A guide

Having trouble with internal links in my template, as they are not directing to the correct URLs. <nuxt-link :to="blog.url" >{{ blog.title }} by {{ blog.author }}</nuxt-link > In my data, I have the foll ...