Managing JSON data structures

In the process of developing a Chrome extension that is intended to extract the YouTube video IDs of the top 3 search results based on an input string, I have encountered a roadblock. The current code snippet looks like this:

var items = [];

function getVideo(searchQuery,item){
    searchQuery = searchQuery.replace(/ /g,'+');
    var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
    //console.log(queryURL);
    $.getJSON(queryURL,function(data){
        items = data.items;
        /*for(var i in items){
            console.log((items[i].id.videoId).toString());
        }*/
    });
}

document.addEventListener('DOMContentLoaded',function(){
    var button = document.getElementById('search');
    var div = document.getElementById('results');
    button.addEventListener('click',function(){
        var base_url = 'https://www.youtube.com/watch?v=';
        var url = [];
        var input = document.getElementById('input');
        var result = input.value;
        getVideo(result);
        for(var i in items){
            console.log(items[i].id.videoId.toString());
            //$('<p>'+(items[i].id.videoId.toString())+'</p><br>').appendTo('#results');
            //url.push(base_url+items[i].id.videoId.toString());
        }
        /*for(var j in url){
            console.log("test");
            console.log(url[j]);
            $('<p>'+url[j]+'</p><br>').appendTo('#results');
        }*/
    });
});

Upon execution in its current form, there is no output in the console. Strangely, making a minor adjustment resolves the issue.

var items = [];

function getVideo(searchQuery,item){
    searchQuery = searchQuery.replace(/ /g,'+');
    var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
    //console.log(queryURL);
    $.getJSON(queryURL,function(data){
        items = data.items;
        for(var i in items){
            console.log((items[i].id.videoId).toString());
        }
    });
}

document.addEventListener('DOMContentLoaded',function(){
    var button = document.getElementById('search');
    var div = document.getElementById('results');
    button.addEventListener('click',function(){
        var base_url = 'https://www.youtube.com/watch?v=';
        var url = [];
        var input = document.getElementById('input');
        var result = input.value;
        getVideo(result);
        /*for(var i in items){
            console.log(items[i].id.videoId.toString());
            //$('<p>'+(items[i].id.videoId.toString())+'</p><br>').appendTo('#results');
            //url.push(base_url+items[i].id.videoId.toString());
        }*/
        /*for(var j in url){
            console.log("test");
            console.log(url[j]);
            $('<p>'+url[j]+'</p><br>').appendTo('#results');
        }*/
    });
});

The only alteration made was moving the console.log statement within the function getVideo. Since 'items' is a globally scoped variable, the issue of scope should not arise. What could be causing this unexpected behavior?

Answer №1

The getVideo function operates asynchronously, causing the items array to remain empty at the start of the first example.

Answer №2

When you make a call to $.getJSON(), it is not synchronous. This means that if you try to loop through the items array immediately after making the call, the array may not have been filled yet because the call is running asynchronously.

Putting console logging within the return block of $.getJSON will work because the call has returned with the data at that point.

If you need to make the call for your JSON data synchronous, consider using an ajax call instead.

You can find more information on how to set async:false in a $.getJSON call here: "Is it possible to set async:false to $.getJSON 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

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

Enhancing Online Presence with Video Gallery Website Development

I'm in the process of creating a website and need help finalizing my video page. I envision a layout similar to this example: https://i.stack.imgur.com/hctui.gif The main feature should be a large video placeholder at the top, followed by several thu ...

Unable to update innerHTML of asp.net literal tag using JavaScript

Here is a snippet of my JavaScript code: <script type="text/javascript">function CountCharacters(idTxtBox, idCharCount) { var maxLimit = 500; var remainingChars = maxLimit - document.getElementById(idTxtBox).value.length; do ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Revealing/disguising elements based on user input changes

I'm currently focused on implementing dynamic search functionality. My goal is to have the #Main div hidden and the #search_list div displayed whenever I type in the input field with the id #search. Also, if I use the keyboard shortcut Ctrl+A & B ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

Attempting to adjust the width of a text animation loaded with jQuery using Textillate, but encountering difficulties

I found a captivating animation on this website: http://codepen.io/jschr/pen/GaJCi Currently, I am integrating it into my project. #content { position: relative; margin-left: auto; margin-right: auto; width: 1000px; height: 700px; } ...

How can I use Angular's $filter to select a specific property

Is there a convenient method in Angular to utilize the $filter service for retrieving an array containing only a specific property from an array of objects? var contacts = [ { name: 'John', id: 42 }, { name: 'M ...

Bringing in CSS variables to a Typescript document

In order to streamline the styling process for our app, we have established a theme.css :root file containing a set of commonly used variables that can be accessed across all other .css files. However, some of our older code follows a similar structure bu ...

Creating a dynamic video background using Html5 and CSS with a scrolling attachment

video { width: 100%; z-index: 1; position: fixed; } I tested this code and it works well, however, the video remains fixed across the entire body of the page... ...

Instructions for showing a "read more" and "read less" link when the text goes beyond a

I am pulling paragraph content from the database and displaying only 300 characters on the screen, with a "read more" option for the user to see the rest of the content. However, I am facing an issue where I also need to include a "less" option for the us ...

Why is the updated index.html not loading with the root request?

I'm currently working on an Angular app and facing an issue with the index.html file not being updated when changes are made. I have noticed that even after modifying the index.html file, requests to localhost:8000 do not reflect the updates. This pro ...

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

Issue with jQuery DataTable: Unable to use column-level filters at the top and maintain a fixed height simultaneously

I am having an issue displaying data in a jQuery DataTable with a column level filter at the top, fixed height, and scroller enabled. Initially, I was able to display the column level filter at the top and it was functioning properly. However, when I set t ...

Is there a way to easily uncheck all MaterialUI Toggle components with the click of a button or triggering an outside

If you have a set of <Toggle /> components in an app to filter clothes by size, and you want to reset all the filters with a single click on a button rather than unchecking each toggle individually. Is it possible to achieve this using materials-ui ...

Can the dropbox option be automatically updated when input is entered in another text field?

I'm working on a form with a dropdown containing category names and a text field for entering the category code. What I need is for selecting a category name from the dropdown to automatically display the corresponding category code in the text field, ...

"Adding a class with jQuery on a selected tab and removing it when another tab is clicked

I have 3 different tabs named Monthly, Bi-monthly, and Weekly. The user can set one of these as their default payroll period, causing that tab to become active. I was able to achieve this functionality by utilizing the following code within the <script& ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

Shared Vue configuration settings carrying over to Jest spec files

For my unit testing of components using VueJS and Jest, I'm incorporating the Bootstrap Vue library for styling. To address console warnings regarding unknown plugins, I've set up a configuration file: import { createLocalVue } from '@vue/t ...

route in mean stack isn't providing a response

I am having trouble creating a controller for /projects that should return all the data in the 'work' collection. The call is completing successfully with a status code of 200, but it is only returning an empty array or 'test:test' if u ...