tips for retrieving global variables from ajax calls using promises

Currently, I am retrieving data and storing it in global variables in a less than optimal way. Here is the current method:

var tranlationJson =
  $.ajax({
     type: "GET",
     url: "translation.xml",
     contentType: "text/xml",
     dataType: "xml",
     success: function (dataSource) {            
        tranlationJson=ToJasonParser(dataSource);
     }
  });

However, I would like to improve this by utilizing promises. The challenge I face is that my code relies on third-party JS files, resulting in something like this:

<script
<script

var translationJson = $.ajax({ ...

<script 111
<script 222

Scripts 111 and 222 contain custom libraries that depend on the translationJson being populated first. How can I ensure that the translationJson is fully loaded before these scripts are executed?

Answer №1

If you want to access a global variable from any of your scripts, you can use the window object. Instead of declaring your variable like

var translationJson = $.ajax({...
, you can assign it directly to
window.translationJson = $.ajax({...
. However, there are a couple of important considerations:

Firstly, you need to handle the timing issue where an ajax request may finish before some of your scripts ask for the variable. One solution is to bind all dependent scripts to the $.ajax({ success: callback function. For example:

$.ajax({
         type: "GET",
         url: "translation.xml",
         contentType: "text/xml",
         dataType: "xml",
         success: function (dataSource) {            
            tranlationJson=ToJasonParser(dataSource);
            someScriptRun(); /* run dependent script here */
         }
    });

Alternatively, you can periodically check for the variable in dependent scripts like this:

var periodicalAttemptToRunScriptDependant = setInterval( function(){
  if( 'object' == typeof window.translationJson ){
    someScriptRun(); /* run dependent script here */
    clearInterval( periodicalAttemptToRunScriptDependant );
  }
}, 1000 );

Secondly, in the provided example, every request for the variable triggers an ajax request because it's not actually a variable but a function. To fix this, consider changing your code to:

var tranlationJson;
$.ajax({
     type: "GET",
     url: "translation.xml",
     contentType: "text/xml",
     dataType: "xml",
     success: function (dataSource) {            
        tranlationJson = ToJasonParser(dataSource);
     }
});

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

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

Would it be possible to continuously send multiple documents to MongoDB using a loop?

I'm facing difficulties in transmitting sensor data to MongoDB using JavaScript. Although I came across options like MongoDB Atlas, I am searching for a more straightforward way to accomplish this. Below is my code: const db = client.db(databaseName) ...

TemplateEditor serving as an interactive form

I'm working on a form that initially displays certain fields upon page load, and additional fields should appear based on the user's selection from a dropdown. These dynamic fields are EditorTemplates. Is there a way to achieve this functionality ...

The utilization of ES Modules within a Next.js server.js

After reviewing a few examples in the Next.js repository, I came across: https://github.com/zeit/next.js/tree/master/examples/custom-server-express https://github.com/zeit/next.js/tree/master/examples/custom-server-koa I observed that these examples ut ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Using JavaScript to make an AJAX request when a dropdown menu from

Looking to update a graph created with Google Chart API using a drop-down menu. Currently facing a few issues. The dropdown is sending a request to the wrong URL. Instead of /graph/, it's sending data to the current page, which is /services/. This ...

How can we automatically delete a message in DiscordJS after a certain amount of time has passed?

I am inquiring about DiscordJS and have a specific question. My query is regarding how to correctly remove a message sent by the bot on Discord. Admittedly, I am new to DiscordJS so please bear with me if this is a basic question. I appreciate all respo ...

Issue: the size of the requested entity is too large

Encountering an error message while using express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/ ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

Prompting a 401 error immediately after attempting to login through the Express REST API

Recently, I've encountered a strange issue with the controller for my login route. It was working perfectly fine yesterday without any hiccups, but suddenly it stopped functioning properly. Despite not making any changes to the code, it now consistent ...

What is the best way to pass an array to a child component in React?

I am having an issue where only the first element of inputArrival and inputBurst is being sent to the child component Barchart.js, instead of all elements. My goal is for the data to be instantly reflected as it is entered into Entrytable.js. EntryTable.js ...

Is it better to have a single object with all required modules in NodeJS, or follow the "standard" paths in the code?

Being a fan of creating global namespaces in javascript, I often use this approach in my app development. For instance, if my application is named Xyz, I typically create an object called XYZ to organize properties and nested objects like so: XYZ.Resource ...

Utilize Twilio to forward messages to a different phone number

I am seeking a solution to automatically forward incoming messages from one Twilio number to another, based on the original sender's number. For example: If I receive a message on my Twilio number "+14444444444" from '+15555555555', I want ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

tips for replicating the impact of http://wearehunted.com

I am trying to emulate the functionality of the website mentioned in the title. Essentially, I want to dynamically update a portion of the webpage using AJAX. However, I am struggling with updating the URL during this process. Any assistance in achieving ...

Using jQuery to send a post request to a PHP script using either JavaScript or PHP

Just a quick question for those with experience. I am working on a page where I have implemented a jQuery AJAX post to another PHP page that contains JavaScript. My concern is, will the JavaScript code also be executed? Another scenario to consider is if ...