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

When iteratively utilizing the setValue() function, an unintentional occurrence of an 'Uncaught error' is encountered

I encountered an issue while trying to update a spreadsheet upon submitting a form. The problem is that after pressing the submit button, the remaining commands are not being executed properly. As a result, I see an error message in the console saying "U ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

I encountered an issue where the error "data.map is not a function" occurs whenever I try to execute a React component

I have implemented the HorizontalScrollbar component and passed data as a prop. When I try to run the HorizontalScrollbar component, I encounter the following error in the console tab of Chrome: Error: Uncaught TypeError: data.map is not a function Horiz ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

When attempting to input a value in the middle of the line, the cursor unexpectedly leaps to the end

I have successfully created a code that prevents spaces at the beginning and special characters in an input field. The code is working perfectly, but there is an issue with the cursor moving to the end when trying to type at the beginning or middle of the ...

Allow only AJAX requests from designated pages with either $_GET or $_POST protocols

Is there a way to verify if the $_GET or $_POST values are coming from a specific page? For instance, imagine an ajax request from page1 sending data to page2.php?q=abc, and page2 will only process the q parameter if it is sent from page1. If I directly ...

Comparing Dates in Node.js using JavaScript and Sorting Arrays based on Date Values

Is JavaScript lacking a basic Date comparison feature similar to Python? Within my Node.js script, these lines are present: console.log(Date(2012,11,10) < Date(2012, 11, 9)) console.log(Date(2012,11,10) > Date(2012, 11, 9)) Surprisingly, both of t ...

Refresh the html of the contenteditable element with the most recent targeted information from the textarea

One issue I'm encountering is quite straightforward: selecting/focusing on a few contenteditable elements, then selecting the textarea and changing the HTML of the last focused element from the textarea. However, my problem arises when the textarea tr ...

The HTML 5 video is not functioning properly on an iPad, and the layout of the iPad has black areas on the sides

Having some trouble with an HTML 5 project where the video plays on Chrome and Safari PC browsers but not on iPad. The task at hand is to get it working in portrait mode only, with the video playing when tapped/clicked. <!doctype html> <!--[if ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

Can you explain the extent to which JavaScript's setTimeout() and clearTimeout() apply?

Approximately 30 seconds after a page is loaded or reloaded, a pop-up will be displayed under certain conditions. The following code successfully achieves this functionality: jQuery(document).ready(function($) { .......... if (localStorage.getItem ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

Ways to retrieve JSON objects from the Controller using ajax

Currently, I am developing a mail validation controller using jQuery AJAX and PHP. Once the message is validated in the PHP controller, I attempt to retrieve it using AJAX and display it on the screen using jQuery. Here is an excerpt of my AJAX code: .. ...

Node js overlooking non-packaged middleware

I encountered an issue with middleware that used to be included in NODE.js but is no longer bundled. I followed the instructions provided here: Node js Error: Most middleware (like session) is no longer bundled with Express and must be installed separatel ...

Reply to changes in the window size *prior to* adjusting the layout

Take a look at the "pixel pipeline" concept illustrated with a vibrant diagram on this page. I am currently working on resizing an element (let's say, a span) dynamically when the browser window is resized. I have implemented this using window.onresi ...

Is it possible to select multiple drop-down lists on a webpage using Python and Selenium?

I am encountering an issue while attempting to click on multiple dropdown lists within a page. I continuously receive an error message stating that my list object does not have an attribute 'tag_name'. Here is my code snippet: def click_follow_ ...

What is the best method to assign each key in an Object to the corresponding value in another Object?

Suppose I have an object called data: { first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade ...

Easily done! Using JavaScript to generate a blinking cursor on a table

Working on a project to develop a dynamic version of the classic game Tic-Tac-Toe... However... Every table cell is displaying an irritating flashing cursor, almost like it's behaving as an input field. Any insights into why this is happening...? O ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...