Retrieve JSON data from the AJAX event's onreadystatechange function

I'm trying to retrieve a JSON object called "encuesta" from an AJAX request and store it in the global variable "jacu." Here's my code:


window.onload = function() {
    tabla = document.getElementById("pregunta");
    jencu = ajax("GET", "datos/encuesta.json", true, "lee")
}

function ajax(metodo, url, bolean, que) {
   var xhr;
   if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
   } else { 
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.onreadystatechange = function() {

           if (xhr.readyState == 4 && xhr.status == 200) {
              if (que == "lee") {
                encuesta = xhr.responseText;
                  encuesta = JSON.parse(encuesta)
               }
           }
    }

   xhr.open(metodo, url, true);
   xhr.send();
}

Answer №1

To ensure that encuesta can be accessed worldwide, it is recommended to define it outside of your function.

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

How to Reset Text Fields with a Button Click in Vue.js?

I am currently working on a layout where I need to loop through text fields and buttons. How can I implement a function for each button that clears only the corresponding fields? Take a look at this fiddle here. <div id="app"> <h2>Each text ...

AngularJS - Retrieving website content through URL using GET request

My current challenge involves fetching the HTML content of a website using AngularJS. Below is the snippet of code I am working with: $http({method: 'GET', url: "http://www.google.com", headers:{ 'Access-Control- ...

Struggling to decode the JSON data from a Rails server using Javascript

I am currently facing difficulties parsing JSON data from my Rails server using Javascript. While I have a good amount of experience with Rails, I am fairly new to JS and keep encountering an unknown error. It would be extremely helpful if someone could g ...

Alter the selected value as the scope of the select is modified

Considering the structure of my application, I am facing an issue with updating select values in the game form when a team is deleted from the list. Here is how my application is organized: mainApp - storageFactory - userController - userFactory - teamCo ...

How can I stop the setinterval function in JavaScript?

My issue revolves around intervals. Upon declaring a function with setInterval, I find that even after clearing the interval, the function continues to execute. Here is my code: if (score == 1) { leftBlinkTimer(0) } else if (score == 0) { leftBlin ...

Issue with Selenium locating element within a GWT application

Looking to extract the text/value from an Element in a GWT app. You can find the app and the Element at the following locations: -navigate to -select "Products" -select "Software" -select "Rotary indexing table" -select "Next" -select "Next" again Y ...

Is it possible to specify a value as an IRI in rml or r2rml?

Currently, I am utilizing the RMLMapper tool to convert JSON data into RDF format. Within the JSON data, there is a specific value that represents a URL. My goal is to utilize this URL as the foundation for an IRI (Internationalized Resource Identifier) fo ...

Exploring AngularJS: Filtering a nested JSON array

Just starting out with AngularJS and I could use some assistance. I have a JSON file that I've been working on, and I'm attempting to create a search filter by ingredient using AngularJS. Can anyone provide guidance? { "id": 01, "recipe- ...

Capturing keyboard input in fullscreen mode does not appear to be functioning

I am currently developing a game using Three.js and I am in need of capturing user input. I have two handler functions set up for this purpose; function press(evt) { console.log(evt); var code = evt.which || evt.keyCode; switch(code) { ...

"Uploading Images Using AJAX: A Step-by-Step Guide

I'm currently facing an issue with a form in my application. The form consists of 2 text inputs and 1 file upload input. While the text inputs are functioning properly with AJAX, the file upload is not working with AJAX. It works fine without AJAX, bu ...

What is causing my mobile navbar to not collapse when the page loads?

I'm having trouble collapsing the navbar on mobile devices. Currently, the navbar only collapses when I manually resize the tab. It seems like the issue is related to it not checking the screen size when the site initially loads. I've attempted t ...

Oh no! There seems to be an unexpected token "<" in my React Native project on Visual Studio Code

When utilizing react-native in VS Code, I encounter an issue where my code fails to compile and throws a syntax error for the "<" symbol. Strangely, many tags work fine with "react-native run-android" from the Terminal. This is the code snippet that I ...

Error encountered in Laravel jQuery dependent dropdown: GET request to http://localhost:8000/dosen/pengajuan/getKK/4 resulted in a 404 (Not Found) response

How can I dynamically populate a dropdown list based on the selection from another dropdown list? I have retrieved the ID from the first dropdown list in the URL, but I am still getting an error like this http://localhost:8000/dosen/pengajuan/getKK/3 Not F ...

Steps to activate a faded background following a form submission triggered by an On change event

My goal is to implement a greyed-out background upon form submission without a traditional submit button. Instead, I want the form to be submitted when the user selects an option from one of three drop-down lists. Here is a snippet of the form: <form ...

Instead of displaying the page as expected, the header information is being

After implementing the jquery load() function to load query results into my page, I noticed that header information and odd characters were appearing on the page. What could be causing this issue? Strangely, this error only occurs in Firefox and Chrome - ...

React Bootstrap ToggleButton firing function multiple times unnecessarily

I've encountered an issue with my react-bootstrap ToggleButtons. Whenever I click on them, the handlePlatformChange() function is triggered twice - first with the correct id and then immediately after with null. I tried including e.preventDefault() in ...

Conceal the sidebar menu by clicking anywhere outside of the menu bar or the designated button

I attempted to create a menu similar to the semantic UI, but so far I have only been able to click the menu button to open and close the menu. I am using a toggle class to display the sidebar, but I'm unsure if this approach is entirely correct: < ...

PrestaShop - Using ajax to update a JSON object with PUT request

I've been attempting to update a JSON object (such as a customer), but I keep encountering the following error: "NetworkError: 405 Method Not Allowed - ..." Here's my code (index.js): var testWebService = angular.module('testWebService& ...

Determining the identity of users who have been authenticated using basicAuth on a Node server during the processing of a POST

Utilizing basicAuth for authenticating POST requests to a specific address. Client side command structure: $.ajax({ type: "POST", accepts: "text/plain", url: "http://localhost:3000/somewhere", data: JSON.stringify(somethin ...

Utilizing Python to extract JSON data from the Ustream API

I am currently working on using simplejson to decode a request from the ustream data api. However, I am encountering an error during the decoding process. As I'm still relatively new to the json library in Python, I am unsure of where to start in trou ...