The onreadystatechange function does not get triggered in Firefox

Below are the codes I have written:

Function for sending an AJAX request and getting a value in return:

function myAjaxCall(){
   var myValue=0;
   var async = false; //I need to make a synchronized request, otherwise the return value is 0
   xmlhttp.open("GET", URL, async);

   xmlhttp.onreadystatechange=function(){
       ...
       myValue = SOMEVALUE;
   };

   xmlhttp.send();         

   return myValue;
}

Another function that makes use of the value returned by myAjaxCall function:

function otherFunc(){
   var x = myAjaxCall();
}

Everything works perfectly except on Firefox browser. This issue arises because in Firefox, the onreadystatechange will not be called if synchronized requests are used.

In my scenario, synchronous ajax requests are necessary. If not used, the return value of myAjaxCall() function will always remain as the initial value "var myValue=0".

How can I solve this problem specific to Firefox?

Answer №1

Instead of using an inline function, consider utilizing a function pointer to prevent encountering this particular problem:

const myAjaxCall = () => {
   let myValue = 0;
   const async = true;

   xmlhttp.open("GET", URL, async);
   xmlhttp.send();
   xmlhttp.onreadystatechange = handleResponse;         
}

const handleResponse = (bar) => {
  let myValue = SOMEOTHERVALUE;
  return myValue;
}

In JavaScript, functions play a significant role in determining the scope, which is why:

  • An anonymous function establishes a new scope, as opposed to the referenced function that operates within the global scope.
  • Moving the function outside of the scope helps in avoiding any potential namespace conflicts.
  • The variable myValue acquires a value within the newly defined scope, whereas it remains undefined in the global scope.

Additionally, make sure to execute the send method before setting up the onReadyStateChange event.

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 jQuery hide and show functions lack precision and are too indiscriminate, requiring a more targeted approach

I am designing a unique contact card that captures a user's name and description from an <input> field and appends the input information into a <div> element. This is the flow I am aiming for... User inputs their first and last name alo ...

Sending data from express js to a different server

Currently, I am faced with a scenario where I need to send a file from Jquery to my Express server and then transfer that request to another server without parsing the file in the Express server. Below are the code snippets I have been using so far: Jquery ...

Every time I try to use AgGrid selectors, they consistently come back with null results, even though the

I currently have an ag grid in my application: <app-my-component> <ag-grid-angular [gridOptions]="gridOptions" (gridReady)="setGridReady()"> </ag-grid-angular> </app-my-component> When running Karma- ...

Obtaining information from Li class using VBA Selenium script

Looking to extract data from li elements with the same class. Here is the VBA code I tried, but it didn't yield any results. Please point out my mistakes. My VBA code: Sub Class_Initialize() Set driver = CreateObject("Selenium.FirefoxDriver") d ...

Limitations of jQuery: onClick function not transferable

I am struggling to achieve the following functionality for my navbar dropdown menus: When the screen size is greater than 992px, I want the navbar dropdowns to open on mouse enter. For screens smaller than 992px, I want the dropdowns to open on ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

The bidirectional functionality of ng-model is not working as expected in my specific application

UPDATE: It seems that setting the controller in the view like ng-controller="SomethingController as Ctrl" and then using it in the model ng-model="Ctrl.myModel" actually works. How surprising! I have been wanting to integrate this particular directive int ...

Achieving success with the "silent-scroll" technique

I've been struggling to implement the 'scroll-sneak' JavaScript code for quite some time now. This code is designed to prevent the page from jumping to the top when an anchor link is clicked, while still allowing the link to function as inte ...

What is the method for applying an event to multiple elements using a jQuery selector?

Imagine a scenario where the markup looks like this: <ul> <li class="one"></li> <li class="one"></li> <li class="one"></li> </ul> Now, with the following jQuery script for an onclick function: ...

Angular 2: Encounter with 504 Error (Gateway Timeout)

I am struggling with handling errors in my Angular 2 application. Whenever the backend server is offline, an uncaught error appears in the console: GET http://localhost:4200/api/public/index.php/data 504 (Gateway Timeout) This is how my http.get me ...

When incorporating an array into a span tag, only the final string is being shown by the loop

I need assistance with changing the content of a span tag every 1.5 seconds, but currently it only displays the final word in the 'list' array. Below is my JavaScript code: var list = [ "websites", "user interfaces" ]; setInterval(fun ...

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

Is there a way to dynamically change text on a webpage without having to refresh the page using data from a database field

Trying to figure out the best approach for this task. Maybe a mix of PHP, MySQL, jQuery, and AJAX? If person 1 is viewing database values on their page and person 2 edits those records from a different computer, can the values update on person 1's sc ...

Incorporate a background only if the specified condition in AngularJS is met, utilizing ng-style

I'm struggling to incorporate a background url style based on a given condition. I tried using data-ng-style, but for some unknown reason, it's not working as expected. I'm not sure where I'm going wrong. data-ng-style="true : {'b ...

Having trouble capturing the CHANNEL_ANSWER event in my node.js script when communicating with Freeswitch

Greetings to all! I have a query regarding freeswitch. Although my experience with freeswitch is limited, I am currently working on connecting my node js script to the freeswitch server. So far, I have managed to establish a successful connection and gene ...

Declare a state in React based on certain conditions

Is it possible to conditionally set up a state based on a certain prop being provided? Consider the following scenario: function Component({scroll, children}) { const [scrollY, setScrollY] = useState(0); useEffect(() => { if (scroll) { ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

React: encountering issues with accessing component props after page refresh

Whenever I try to reload the 'details' page (not the homepage) on my app, I encounter the following error: "TypeError: Cannot destructure property 'flag' of 'country' as it is undefined." It seems that the data is ...

I am attempting to create a slash command response using discord js that includes image attachments, but I am struggling to get it to work correctly without using embed

My goal is to enable my bot to respond with images when a slash command is used. I am planning to use MessageAttachment to retrieve the image URL and then call it using await interaction. However, I encountered this error in the logs: I am using Discord.j ...

Tips for storing a string or object in a Firebase database

I'm looking for some guidance on how to save a string or object to the Firebase database using JavaScript. I'm currently trying to do this on codepen.io. Here's what I've attempted so far: // Setting up Firebase app const firebaseConfi ...