The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not.

function populate_selectbox()
{               
var ajaxRequest;

try {
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e) {
    // Internet Explorer Browsers
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
        // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}

var queryString = "?callFunction=get_all_data";
//console.log(queryString);

ajaxRequest.open("GET", "php/shares.php" + queryString, true);
ajaxRequest.send(null);

var optiondata ="";

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() 
{

    if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) 
    {
        //console.log("IF....");

        var resp = JSON.parse(ajaxRequest.responseText);
        //console.log(resp)

        for (var i = 0; i < resp.data.length; i++) 
        {
            if(i === resp.data.length -1)
            {
                optiondata += "'"+resp.data[i].name+"'"; //For the last name in the loop
            }
            else
            {
                optiondata += "'"+resp.data[i].name+"',";
            }

        }

        console.log(optiondata); //This works
        return optiondata; //This returns undefines
    }    
};  
}

Could you explain why there is a discrepancy in the output?

Answer №1

When dealing with ajax callbacks, remember that you cannot return any data using the "return" keyword due to the asynchronous nature of ajax requests.

Instead, create your own callback function and pass the results into it.

function myAjaxFn(..., done) {
    // ...
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          done(xmlhttp.responseText);
        }
      }
    xmlhttp.open("GET","ajax_info.txt",true);
    xmlhttp.send();
}

Alternatively, consider using promises as a more efficient solution:

Answer №2

Consider using the Promise object for asynchronous operations.

    var queryString = "?callFunction=get_all_data";
    var request = function(queryString) {
      return new Promise(function(resolve, reject) {
        var ajaxRequest = new XMLHttpRequest()
        , optiondata = "";
        ajaxRequest.open("GET", "php/shares.php" + queryString, true);
        ajaxRequest.onload = function() {
          if (this.readyState === 4 && this.status === 200) {
            // do something
            var resp = JSON.parse(this.responseText);
            console.log(resp);
            for (var i = 0; i < resp.data.length; i++) {
              if (i === resp.data.length -1) {
                optiondata += "'"+resp.data[i].name+"'"; 
              }
              else {
                optiondata += "'"+resp.data[i].name+"',";
              }
            }
            console.log("onload:", optiondata); 
            resolve(optiondata); 
          } else {
            reject(this.status)
          }    
        };  
        ajaxRequest.send(null);
      });
    };

    request(queryString).then(function success(data) {
      console.log("returned data:", data)
    }, function error(err) {
      console.log(err)
    });

    var queryString = "?callFunction=get_all_data";
    var request = function(queryString) {
      return new Promise(function(resolve, reject) {
        var ajaxRequest = new XMLHttpRequest()
        , optiondata = "";
        ajaxRequest.open("GET", "https://example.com/data.txt", true);
        ajaxRequest.onload = function() {
          if (this.readyState === 4 && this.status === 200) {
            // do something
            optiondata = this.responseText;
            console.log("onload:", optiondata); 
            resolve(optiondata); 
          } else {
            reject(this.status)
          }    
        };  
        ajaxRequest.send(null);
      });
    };
    
    request(queryString).then(function success(data) {
      console.log("returned data:", data)
    }, function error(err) {
      console.log(err)
    });

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

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Can I use npm's jQuery in an old-school HTML format?

I am looking to incorporate jQuery into a project without having to rely on the website or CDN for downloading the library. As someone new to npm, I am curious to know if following these steps would be advisable or potentially problematic down the line. Wh ...

Change the state of items in a React component to either disabled or active depending on the active items list retrieved from the API

Obtained from the API, I have a collection of buttons that are displayed for filtering: For instance: button2 button4 button5 Assuming there are a total of 5 buttons. button1 and button3 are supposed to be in a disabled or inactive state (appearing ...

Encountering a browser error when trying to access a C# method via AJAX: Javascript

I'm having trouble connecting to my Webservice. I keep getting an error 404, even though everything seems like it should be working fine. The issue started when I moved the code from my *.cshtml file into a separate .js file. The Javascript file is l ...

Discovering and revising an item, delivering the complete object, in a recursive manner

After delving into recursion, I find myself at a crossroads where I struggle to return the entire object after making an update. Imagine you have an object with nested arrays containing keys specifying where you want to perform a value update... const tes ...

What measures do websites such as yelp and urbandictionary implement to avoid multiple votes from unregistered users?

It is interesting to note that on urbandictionary, you do not need to be logged in to upvote a definition. For example, if you visit and upvote the first word, it will record your vote. Even if you open an incognito window and try to upvote again, or use ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

Unlocking the power of accessing nested data in JSON files dynamically

Building a new feature that allows users to input a word, choose the language, and receive the definition along with an example using the API service. To retrieve the desired data at position 0 of "exclamation" in the "meaning" section. This ensures that ...

Displaying dates in Material UI datepicker is not working

My current setup involves using Material UI v14.4 with React, and I have encountered an issue with the DatePicker component not displaying the dates correctly as shown in the attached screenshot. Strangely, there are no visible error messages either. Any s ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

Multiple minute delays are causing issues for the Cron server due to the use of setTimeout()

I have an active 'cron' server that is responsible for executing timed commands scheduled in the future. This server is dedicated solely to this task. On my personal laptop, everything runs smoothly and functions are executed on time. However, ...

The application experiences crashes when the tablet is rotated, happening while in the development stage

For my web-based Android application project, I am utilizing PhoneGap and Eclipse IDE on a Windows platform. My focus is specifically on Tablet development, more precisely on the Samsung Galaxy Tab 10.1. To develop, I use Eclipse and test the app on the ...

Utilizing React JS to Activate the Glyphicon Calendar Icon on Click

Could someone please advise on how to make the calendar glyphicon activate the datetime picker upon clicking? I have a button currently but it is not functional. I've been searching for React-specific solutions without success. <div className={cla ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

Managing conflicting eslint rules within the AirBNB configuration can be challenging, but here are some best

Hey all, I'm new to Vue and I'm attempting to create a POC. I've set up ESLint with the AirBNB configuration, but I've run into an issue. Here is the section of code where I'm encountering problems within my Axios call: .catch((er ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

Encountering special symbols in the ID of a form element triggers an error message in jQuery validator, stating 'Unrecognized expression'

One of the challenges I am facing is that I have a form with elements that have ids containing special symbols. For example: The id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[@type='qualification' and @position='prefi ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...