Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why?

Ajax Call

var ajax = new XMLHttpRequest();
  var data = 'data.json';
  var url = 'http://localhost:8888/';
  ajax.onreadystatechange = function() {
    if (ajax.readyState === 4 ) {
      if(ajax.status === 200){
        callback(ajax.responseText);
      } else if(ajax.status === 400) {
        console.warn('404');
      } else {
        console.warn('bad' + ajax.responseText);
      }
    }
  };
  ajax.open('GET', url+data, true);
  ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  ajax.setRequestHeader('Access-Control-Allow-Origin', '*');
  ajax.send(data);

JSON

{
    "video": {
    "mp4": "http://localhost:8888/500x.mp4", 
    "webm": "http://localhost:8888/500x.webm", 
    "title": "video1" },

    "video": {
    "mp4": "http://localhost:8888/dodge.mp4", 
    "webm": "http://localhost:8888/dodge.webm", 
    "title": "video2" },

    "video": {
    "mp4": "http://localhost:8888/500x.mp4", 
    "webm": "http://localhost:8888/500x.webm", 
    "title": "video3" }
}

Please refer to the callback function below, where getVideoURL is my Ajax Call Function

inject : function(tabId, infos, tab){
    if(doner.activated && infos.status === 'complete' && doner.filters.isYoutubeUrl(tab.url)){
      doner.getVideoUrls(function(data){
        chrome.tabs.executeScript(tabId,{
          code : '!function(e){"use strict";console.debug("starting injection");var t=document.createElement("script");t.src=chrome.extension.getURL("scripts/injectedScript.js"),t.onload=function(){this.parentNode.removeChild(this)},(document.head||document.documentElement).appendChild(t);var o=document.getElementById("extAdd");o&&o.parentNode&&(console.log("removing",o),o.parentNode.removeChild(o));var n=document.createElement("iframe");document.getElementById("player-api").setAttribute("style","padding:0;");n.id="extAdd",n.setAttribute("style","border-style:none;-webkit-appearance:none;border:0;outline:none;"),n.className="html5-video-player el-detailpage ps-null hide-info-bar autohide-controls-aspect autohide-controls-fullscreen autominimize-progress-bar-non-aspect ad-created endscreen-created captions-created captions-loaded ytp-block-autohide paused-mode",n.setAttribute("allowfullscreen","true"),n.src=chrome.extension.getURL("iframe/iframe.html?id="+e);var d=document.getElementById("player-api");d.insertBefore(n,d.childNodes[0]);}("' + encodeURIComponent(JSON.stringify(data)) + '");',
          runAt: 'document_start'
        }, function(){
          // get the popup and increase the watched value
          chrome.storage.local.get({ 'watched' : 0 },function(item){
            console.log(item);
            chrome.storage.local.set({'watched':item.watched + 1});
          });

          console.log('injected');
        });
      });
    }
  }

Answer №1

Your JSON object currently has the property video declared multiple times, with only the last declaration being retained in memory.

To improve your JSON structure, consider using an array like this:

[
    {
        "video": {
            "mp4": "http://localhost:8888/500x.mp4",
            "webm": "http://localhost:8888/500x.webm",
            "title": "video1"
        }
    },

    {
        "video": {
            "mp4": "http://localhost:8888/dodge.mp4",
            "webm": "http://localhost:8888/dodge.webm",
            "title": "video2"
        }
    },

    {
        "video": {
            "mp4": "http://localhost:8888/500x.mp4",
            "webm": "http://localhost:8888/500x.webm",
            "title": "video3"
        }
    }
]

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

Navigate the array and divide the elements into separate values

For a project I need to upload files, wherein the data is organized within an object like [5.76516834507, 50.8474898368], [5.76115833641, 50.8453698247]. The task here is to extract and store the first value as latitude: 5.76516834507 and the second value ...

"Converting an HTML file to a Word file using PHP - a step-by-step

Help needed with converting an HTML file to MS Word using PHP code. Below is the code I am using: include("connection.php"); extract($_REQUEST); ob_start(); include("counties/$county_name/$file"); $html_content = ob_get_contents(); ob_end_clean(); header ...

Having trouble locating HTML elements by their id when typing into a box using cy.get in Cypress with JavaScript

I am a novice in working with cypress and HTML, and I am currently attempting to enter an address in the specified address field. <input type="text" title="Street Address 1" name="billing[street][]" id="billing:street1" value="" class="input-text " ...

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response? .controller('items_ctrl',['$scope','$http',function($scope,$http){ $scope.shop_id=localStorage.getItem(" ...

Ways to eliminate a bootstrap modal that has been added using jQuery?

After realizing I needed a script to dynamically insert custom Bootstrap modals instead of having empty static modal HTML on every page, I created a solution. I defined a variable for the modal 'shell' HTML and appended it to the body when clicki ...

Java Script Custom Print Preview: A unique way to showcase your content

Is there a way to create a custom print preview dialog similar to the browser's print preview using Java Script? I am working on a book reader application that requires customization of the print preview dialog for page counting, automatic pagination, ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

The task "npm compile" could not be located

I am having some trouble creating a smart contract and running the code. Initially, I encountered an error with the outfiles, so I decided to replace the code in the launch.json file as shown in the screenshot. However, now I am facing a different error ...

Rotating camera independently from its parent in Three.js

I have a scenario where an Entity is traversing a CatmullRomCurve3 path, moving left with the left or down arrow keys and right with the right or up arrow keys. Initially, I encountered an issue where I wanted the Entity to face perpendicular to the path ...

When you invoke a function within Angular 1.5 as a fresh component emerges

I have a component where clicking on a button triggers the invocation of another component. model.alert = function () { modalInstance = $uibModal.open({ template: '<abc-xyz return-value="model" on-cancel="Cancel()">& ...

Using jQuery to append text after multiple element values

I currently have price span tags displayed on my website: <div> <span class="priceTitle">10.00</span> </div> <div> <span class="priceTitle">15.00</span> </div> <div> <span class="priceTitle">20.0 ...

Issues with making cross-domain requests using jQuery and PHP

I have stumbled upon a similar question that has been asked before, but unfortunately, the answer provided did not give me enough guidance to identify where my code is incorrect. I apologize if this question resembles a previously existing one; I have spen ...

Using Python to loop through and make changes to JSON elements

I am facing a challenge with the following data structure in JSON format: { "taskDefinition": { "containerDefinitions": [ { "memoryReservation": 1040, "mountPoints": [ ], "name": "staging-web1", "image" ...

creating a JSON object

Exploring JSON for the first time and I have a couple of questions: Is it possible to create a JSON object using the 'data-id' attribute and have it contain a single array of numbers? Even though I have the code to do this, I am facing difficul ...

Tips and techniques for implementing push notifications in front-end applications without the need for a page refresh

I am working on a Python program that inserts data into a XAMPP database. I am looking for a way to continuously monitor the database for any changes and automatically send updates to the frontend without relying on click events. Is there a method simila ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...

Ways to retrieve information from a $$state object

Everytime I try to access $scope.packgs, it shows as a $$state object instead of the array of objects that I'm expecting. When I console log the response, it displays the correct data. What am I doing wrong? This is my controller: routerApp.controll ...

Dynamic data in highcharts pie charts allows for the customization and selection of colors

I am working with a pie chart that looks like this { type : 'pie', data : [], //dynamic data goes here center : [50, 15 ], size : 80, showInLegend : false, dataLabels : enabled: true, } Now, I am interested in changing the color of ...