How can I access the result of a getJSON promise within the $.when method?

I am working on a piece of code where I aim to collect data from 2 getjson calls and store it in an array only when both calls have successfully completed. However, I encountered the following error:

resultFromUrl1.feed is undefined
var entry1 = resultFromUr11.feed.entry;

Upon inspecting the F12 console, I confirmed that both getjson calls were executed successfully, yet no data was being pushed into the array. How can I resolve this issue? Additionally, should I be using $.when(url1Promise, url2Promise).then or $.when(url1Promise, url2Promise).done?

<javascript>
     var files = new Array();

        function pushtoArray() {

            //first getjson call
            var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
            var url1Promise = $.getJSON(url1, function (data) {
                console.log("url1 success");
            });//end of ajax call

            //second getjson call
            var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
            var url2Promise = $.getJSON(url2, function (data) {
                console.log("url2 success");
            });//end of function

            $.when(url1Promise, url2Promise).then(function (resultFromUrl1, resultFromUrl2) {
                var entry1 = resultFromUrl1.feed.entry;
                var entry2 = resultFromUrl2.feed.entry;

                var entry = entry1.concat(entry2);

                $(entry).each(function () {
                    // Column names are name, age, etc.
                    count++;
                    files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
                            alert(files.length);
                            print_r(files);
                            console.log(files);


                });


            });
        }//end of function 
            </javascript>
            <body onload="pushtoArray()">

Answer №1

Dealing with jQuery ajax functions and $.when() can be a bit tricky. In the variable resultFromURL1, you will actually find an array of three values structured like this: [data, textStatus, jqXHR].

To work with this data, make sure to update your code as follows:

var entry1 = resultFromUrl1[0].feed.entry;
var entry2 = resultFromUrl2[0].feed.entry;

Furthermore, it is recommended to include an error handler within your $.when().then() sequence to monitor for any potential issues during the execution of your getJSON() requests.

Answer №2

When I tested your sample using the following link: "", everything ran smoothly.

The data retrieval was successful. To access the retrieved data, simply use the following code:

resultFromUrl1[0].feed.entry
resultFromUrl2[0].feed.entry;

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

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

How can a "Loading" message be displayed while external JavaScript is loading?

I have mastered the art of using JS or jQuery to showcase a "Loading" message during the loading process. Currently, I am working on a sizeable web application that relies on various JS dependencies, and I am seeking a way to exhibit a "loading" message wh ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Button's focus event doesn't trigger on iPad

I am facing an issue with adding a bootstrap popover to my website. The popover should appear when the user clicks a button using the focus event. This functionality works fine on desktop browsers, but on the iPad, it seems like Safari on iOS does not trig ...

Efficient Ways to Store Text and Images in Vue.js

I have developed a tool that enables users to upload an image and overlay custom text on it, which can be viewed and edited in the browser. My query is whether it is feasible to save the combined image and text as separate files (e.g., jpg/png) using VueJS ...

Theme.breakpoints.down not being acknowledged by MUI breakpoints

The Challenge: Implement a hamburger menu to replace the navMenu on tablet and smaller screens After successfully compiling in VS code terminal, encountering an error in the browser: Error Message: TypeError: Cannot read properties of undefined (reading ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

Filtering data from MongoDB within the controller logic

I have a query in my controller that retrieves records from a MongoDB document. However, I need to filter the incoming records by a field archived == true. The current code works fine without any filters. I'm trying to figure out where to add the fil ...

Uploading Files in .NET Using WebMethod and XHRHttpRequest

Attempting an asynchronous file upload using JavaScript with a WebMethod in VB.NET JavaScript: xhr.open('POST', "upload.aspx/upload", true); xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); var formData = new FormData ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Separating Angular controllers into their own files can help prevent errors like "undefined is not a

I am currently revamping some Angular code and my goal is to organize things by type, such as keeping controllers in a separate folder. Currently, I have two controllers and an app.js file. However, I am encountering an issue with the error message "undef ...

Resetting forms in AngularJS 1.5.6 with ng-messages functionality

I have been searching for solutions on Stackoverflow regarding how to reset a form, but I am still not able to figure it out. Even though the input was valid, the error message kept showing up. Upon debugging the application, I noticed that the message was ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

Exploring the process of dynamically inserting choices into an array of HTML dropdown menus using a combination of Php, AJAX, and jQuery

My task involves populating an HTML array of 10 select fields with jQuery every time a div-popup is called. The purpose of this form is to facilitate the batch approval of staffing requests for hundreds of employees by upper management, organized by depart ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

clear the input field of any entered text type

Just starting out with Javascript! Below is some code: This code is taken directly from the HTML page <form action="#" id="ToolKeywordSearch"> <input type="text" class="ProductFinderText" id="ToolSearchField"onblur="if(this.value==& ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...