Saving the content of XMLHttpRequest.responseText into a variable

I'm fairly new to using XMLHttpRequests, but I've been experimenting with the cross-origin function in Google Chrome extensions. My code works well (I am able to receive the data I need), however, I am facing issues when trying to store it within the 'response' variable.

I could really use some guidance on this.

function getSource() {
    var response;
    var xmlhttp;

    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             response = xmlhttp.responseText;
                 //Data is correctly set here
        }
        //Still holding value here
    }
    //Suddenly becomes undefined here.

    xmlhttp.open("GET","http://www.google.com",true);
    xmlhttp.send();

    return response; 
}

Answer №1

The onreadystatechange function operates asynchronously, meaning it does not block the execution of subsequent code until it completes.

Therefore, your current approach is incorrect. In asynchronous programming, it is common to utilize callbacks to ensure that certain actions are taken precisely when the onreadystatechange event triggers, allowing you to retrieve the response text at the correct time. Here is an example of how a callback can be used in asynchronous code:

function fetchContent(callback) {
    var response, xhr;

    xhr = new XMLHttpRequest;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200 && callback) callback(xhr.responseText);
    }

    xhr.open("GET", "http://www.example.com", true);
    xhr.send();
}

Think of it like using setTimeout, another asynchronous operation. The following code will not wait for 100 trillion seconds before completing, but rather finish immediately and then trigger the timer's function after the specified delay. However, by that point, the variable assignment is meaningless as it is not accessible globally and nothing else exists within its scope.

function demo()
{   
    var x;
    setTimeout(function () { x = 1; }, 100000000000000000); // high number for demonstration purposes only
    return x; // returns undefined since the function has executed completely, but the setTimeout has not yet occurred
    x = 1; // performing this after the return statement has no impact
}

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

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

What causes the Ajax call to return null upon the initial request?

I am currently facing an issue with my jQuery typeahead control. It is supposed to display a list of available students and narrow down the list as the user types more letters. However, I'm encountering a problem where it returns null when the user ty ...

Can anyone help me understand how to serve static files in relation to subdirectory index files using express.js?

I am currently working on a project with the following structure: /applications /applications/testRoute /applications/testRoute/index.html /applications/testRoute/test.js /applications/server.js As part of this project, I am running an express app that co ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

Rails AJAX Voting Functionality Implementation Bug

I'm currently working on a social app where I have successfully implemented the Acts As Votable gem. However, I am facing an issue with getting it to work via ajax in order to prevent page refreshes that disrupt the user's browsing experience. U ...

Generate a collection of LatLng coordinates to represent a worldwide grid

I'm in search of a quick and easy solution, like a simple library or similar tool, that would allow me to call a function like createGlobalGrid(1000) and automatically generate a list of points on a geospatial surface, ensuring that each point is no m ...

Encasing functions within brackets - `(function() { })()`, and utilizing `.call()`

After spending some time writing JavaScript, I decided to delve into CoffeeScript. One thing that caught my attention is how CoffeeScript compiles functions in the following format: (function() { }).call() I've also come across functions written th ...

Update depth has exceeded the limit, the useEffect in React is causing issues

I encountered a strange error while working with the component below. The error seems to occur only when I make changes to the file, like altering a default prop, and then saving the file. I believe the issue stems from the props triggering a re-render, as ...

Determining when the clear button is clicked in a v-select (vue-select) detection strategy

While working on creating a drop-down using v-select, I encountered an issue. After selecting an option, I needed to clear the drop-down and revert the option array back to its initial stage upon clicking the clear button. I attempted various methods such ...

JavaScript Functions for Beginners

I'm currently facing some challenges with transferring the scripts and HTML content from the calendar on refdesk.com. My task involves moving the JavaScript to a separate stylesheet and utilizing those functions to replicate the calendar on an HTML pa ...

Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts. In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (. ...

What are the best methods for saving long-term offline data in Progressive Web Apps using browser storage?

Can permanent data be stored in offline storage within a web browser? I have been struggling to find a solution and would appreciate any help you can provide. I've gone through some tutorials but haven't found them to be useful. Thank you in ad ...

Ways to execute function when state changes, excluding initial loading

I need to trigger a function when the state's data changes, excluding the initial load. Below is my code snippet: const Page = (props) => { const { data } = props; const arrowDirection = (item) => { if (item.arrow === 1) { return ...

Tips for initiating a function through scrolling

I need to implement animations triggered by scrolling past a specific point on the page. However, I seem to be struggling with the syntax for calling the animation function using the scrollTop property. I did test it with alert and it worked fine. var ill ...

Issue in Wordpress: ReferenceError - '$' is not defined

Currently utilizing WordPress and attempting to access the following code snippet. I am encountering an error on the last line }(jQuery)); (function($) { $(function () { // Slideshow 3 $("#slider3").responsiveSlides({ auto: true, pag ...

What is the best way to transform the words in my JavaScript array into clickable links?

I am working on a search bar that autofills words and I want to turn those autofilled words into clickable links. For example, if I type "locations" in the search bar, I want it to autofill the word "locations" and turn it into a link that directs me to pa ...

Tips for showcasing and allowing editing of three table data in an MVC3 view

I am trying to find the best way to display 3 data tables in a view, all of which are pulled from the same table in the database. My idea is to utilize 3 separate partial views within index.cshtml and retrieve the data using one stored procedure. I also wa ...

Filtering data in Vue.js using JSON specifications

How can I display only the names in the data? I currently have cards filtered by cities <div v-for="item in stationCityData"> <div v-for="option in filteredCity" style="background:#eee;padding: 20px"> <!-- <div v-for="option ...

constructing a new array instance through pushing JSON documents

There are two objects which I have defined: var id = "one"; var arrobj = Array[2] 0: Object name : "a" desc : "desc1" 1: Object name : "b" desc : "desc2" My goal is to create the object in the following structure ...