Using XMLHttpRequest to fetch a JSON object

Having trouble with returning an object from the getMine function in Javascript? Even though you try to print out the object, it keeps showing up as undefined. How can you successfully return the obj within this function?

            function getMine() {
                var httpRequest = new XMLHttpRequest();
                httpRequest.onreadystatechange = function() {
                    if (httpRequest.readyState === 4) { // request is done
                        if (httpRequest.status === 200) { // success
                            var obj = JSON.parse(httpRequest.responseText)
                            return obj;
                        }
                    }
                };
                httpRequest.open('GET', "/getTest");
                httpRequest.send();
            }
            var rs = getMine();
            console.log("2", rs);

Answer №1

When utilizing getMine for an ajax call, it operates asynchronously. Therefore, logging the value of rs immediately after calling getMine() will not work as the ajax call is still in progress. To address this issue, include your console.log within the onreadystatechange callback:

httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var obj = JSON.parse(httpRequest.responseText);
            console.log('responseText: ', responseText);
            return obj;
        }
    }
};

If you require action based on the return value, consider exploring the use of promises to manage the asynchronous completion of an ajax call.

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

Implementing async and await after making a fetch request

I am in the process of updating my code from using callbacks to utilize async and await. However, I am a bit confused on how to properly implement it within my current setup. The current setup involves: Clicking a button that triggers the clicker functi ...

No more Ajax needed for downloading links in SilverStripe GridField

Following a previous issue I encountered here, I needed to insert a link into a SilverStripe GridField for each item. Now, the plan is to replace the link with a custom action to trigger the download. To achieve this, a custom GridFieldAction is required. ...

Can I safely keep a JWT in localStorage while using ReactJS?

As I work on developing a single page application with ReactJS, one question comes to mind. I came across information indicating that using localStorage may pose security risks due to XSS vulnerabilities. However, given that React escapes all user input, ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Discover if one dictionary is within another (updated edition)

I need help finding a method to determine if one dictionary is included within another: big = {"result": {"code": "1000", "msg" : "oh yeah"} } small = {"result": {"code": "1000"}} test(small, big) # expected output: True ( small <= big ) Existing sol ...

What are the steps to store my information in MongoDB with the help of Expressjs?

As a backend developer beginner, I am currently working with an array called Movie using expressJS. My goal is to save this array in a MongoDB database, specifically using Mongodb Atlas. Any help or guidance on this process would be greatly appreciated. I ...

Placing the template code underneath the existing code within the Handlebars layout.hbs file

I'm currently working on a project using Express Handlebars. I have a template called foo.hbs that contains some JavaScript code which I need to insert below the script tags in the layout.hbs file: <!DOCTYPE html> <html> <head> ...

How can we use Ruby on Rails (ROR) as a server-side language to create a post method that retrieves

Is there a way to retrieve data from the client side using an action called create? Specifically, how can data be fetched using the post method within the create function? Essentially, I am looking for guidance on accessing data from the client side throug ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

Struggling to get the Content Security Policy (CSP) to function properly within Next.js

I have been working on a NextJS project and I am currently facing a challenge in setting up secure headers in the next.config.js file of my project. I have attempted various solutions found online, but unfortunately, none of them seem to be working for me ...

Getting a portion of a href link in Java using Selenium

I am looking to compare the current URL in Google Chrome with a specific href link that contains two URLs. I need to extract the first link from this specific href link: click here <a href="http://pubcontentqa.perion.com/dz2/html/interstitial.html?http ...

"Issues Arising from Compatibility between Internet Explorer, jQuery,

I need help creating a function that will transfer items from the basket to the cart. The code I have written works well in Firefox and Chrome, however, it is not recognizing the products. var modals_pool = {}; $('.deal_order_btn').on('clic ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

Experiencing difficulty receiving a full response from an ajax-php request displayed in a div

Having trouble getting a response in a div from an ajax request triggered by an onclick event in a form and a PHP page. Here's the code: <html> <head> <script language="javascript"> function commentRequest(counter) { new Ajax. ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

The instantiation of com.google.ads.AdView was unsuccessful due to a java.lang.ClassNotFoundException error for org.json.JSONException

I encountered an issue with my main.xml file where I am seeing the error message "com.google.ads.AdView failed to instantiate." When I click on the show message, it displays a source not found error. I am not very experienced in development, and I learned ...

Sending a request via AJAX to retrieve a complicated object

Programming Environment: ASP.NET, jQuery Below is the AJAX call I am using: var tempVar = JSON.stringify({plotID:currentId}); $.ajax({ type: "POST", url: "testPage.aspx/getPlotConfig", data: tempVar, contentType: ...

Serializing a Map containing key-value pairs represented as a case class using circe

Here is a simplified code snippet that involves a Map with key and value as case classes. The key and value objects are successfully serialized using circe. However, there is a challenge in serializing Map[CaseClassKey, CaseClassValue] with circe. //////de ...