Populate a dropdown with values from a JSON object

There is a function in my code that retrieves JSON text from a specific website:

window.onload = function httpGet()
{
    var xmlHttp = null;
    var box = document.getElementById("http") //just for testing
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://link_to_Json_Text", false );
    xmlHttp.send( null );
    box.value += xmlHttp.responseText; //just for testing
    return xmlHttp.responseText.toJSON();

}

This will show the results as:

    {
  "head": {
    "vars": [ "uri" , "label" ]
  } ,
  "results": {
    "bindings": [
      {
        "uri": { "type": "uri" , "value": "http://tematres.befdata.biow.uni-leipzig.de/vocab/?tema=751" } ,
        "label": { "type": "literal" , "xml:lang": "en" , "value": "15n" }
      } ,
      {

Then I utilize this function to extract the values of the JSON as an object:

var results = httpGet().results.bindings.map(function(el){
    return { uri: el.uri.value, label: el.label.value };
});

Subsequently, I aim to populate an HTML select menu with the values obtained from the second function.

Nevertheless, there seems to be an issue regarding the correct calling of the second method from the first one, as the console displays errors like :

Uncaught ReferenceError: httpGet is not defined

The goal is to make use of the value from label in order to populate the select menu.

Answer №1

To achieve this, simply link the success event to the request:

window.onload = function() //No function name needed
{
    var xmlHttp = null;
    var box = document.getElementById("http") //just for testing
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://link_to_Json_Text", false );
    xmlHttp.send( null );
    xmlHttp.onreadystatechange=function()
    {
       if (xmlHttp.readyState==4 && xmlHttp.status==200)
       {
          var results =xmlHttp.responseText.toJSON();
          results.bindings.map(function(el){
              return { uri: el.uri.value, label: el.label.value };
          });
       }
    };
}

This code initiates the httpGet request and waits for the request to finish (readyState ==4) before executing the functionality to process the results.

However, I would suggest considering using jQuery if possible, as it is much simpler to work with Ajax compared to native JS.

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

Personalize the color scheme for your timeline paper

I am interested in customizing this specific example of a personalized timeline: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Timeline from '@material-ui/lab/Timeline'; import Timeli ...

Pattern to identify a 32-character string comprising a mix of letters and numbers

I am in search of a JavaScript regex pattern that can identify strings with the following format... loYm9vYzE6Z-aaj5lL_Og539wFer0KfD pxeGxvYzE6o97T7OD2mu_qowJdqR7NRc gwaXhuYzE6l3r1wh5ZdSkJvtK6uSw11d These strings are always 32 characters long and conta ...

Guidelines on maintaining an active getSelection with JavaScript

I need help figuring out how to change the font size of selected text within a div without losing the highlight/selection when I click a button. Can someone assist me in keeping the text highlighted while also resizing it upon clicking the button? ...

Json.stringify seems to be failing to save data in LocalStorage

When broken down to its simplest form: localStorage.setItem('index0', JSON.stringify(playerInventory[lootArray[0]])); var retrievedIndex0 = localStorage.getItem('index0'); console.log('retrieved0:'+retrievedIndex0 ); //Disp ...

Exploring the Contrasts: JSON versus JSONB within Postgres

Can you explain the distinctions between JSON and JSONB data types in PostgreSQL? What are the scenarios in which each should be utilized? What advantages or drawbacks do they have compared to one another? ...

What is causing the child table (toggle-table) to duplicate every time a row in the parent table is clicked?

After creating a table containing GDP data for country states, I've noticed that when a user clicks on a state row, the child table displaying district GDP appears. However, there seems to be an issue with the child table as it keeps repeating. I&apos ...

The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/ My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine. I was creating my own custom image viewer, and everything was ...

Tips on transferring information from AngularJS to a remote server using ngResource

Looking for guidance on utilizing the ngResource module? To send data to a server. To retrieve data from a server. I am attempting to send data to a Solr server. Utilizing AngularJS API. Using npm package manager to install packages to my application. Th ...

Obtaining a group object when the property value matches the itemSearch criteria

What is the best way to extract specific objects from a group when one of their properties has an array value, specifically using _.lodash/underscore? { "tileRecords" : [ { "tileName" : "Fama Brown", "tileGroup" : ["Polished", "Matt", ...

What issues are there with JavaScript?

I encountered an issue with my JavaScript code where it is not producing the expected result. var arr = new Array(); var firstobj = { cta: 0, ccc: 0, crc: 0 } for (var ta = 1; ta <= 10; ta++) { arr[ta] = firstobj; } arr[6].cta = 1; conso ...

Modifying the HTML attribute value (of input) does not impact the value property

After inputting a single tag, I ran the following code in my Chrome console: https://i.stack.imgur.com/ySErA.jpg The result was unexpected for me. According to what I have read in a book, when I change an HTML attribute, the corresponding property should ...

What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row? I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this. I'm sure man ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

What is the best way to prevent the response from being wrapped in "content" when sending back ViewModel from a controller action?

Using Zend Framework 2 with an AbstractRestfulController where the getList action is implemented in the following manner: public function getList() { return new ViewModel(array( 'entities' = array(1 => array(/*..*/), 2 => array ...

When attempting to instantiate a list from JSON in Angular, the type '{}' is lacking the following properties compared to type 'Datos[]'

I'm encountering issues when trying to incorporate JSON data into my Angular application. My Process: Importing the JSON file into a variable: import _data from '../../../assets/data.json'; Following the advice from responses in this t ...

The value chosen by the user is not retained by the Select function

Having some trouble with a simple select issue in Angular that is causing my select options to disappear after clicking on them. Here's my code: var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.searchFilt ...

Effortlessly Concealing Numerous Elements with a Single Click in Pure JavaScript

I have successfully created an HTML accordion, but I am facing an issue. I want to implement a functionality where clicking on one accordion button will expand its content while hiding all other accordion contents. For example, if I click on accordion one ...

Pull all Spark files prefixed with "part-*" from AWS and combine them into one consolidated local file

After running a Spark job using Databricks on AWS, I utilized the following code to save the results: big_old_rdd.saveAsTextFile("path/to/my_file.json") This stored the output in an S3 bucket on AWS, resulting in a directory path/to/my_file.json with var ...

JavaScript error: You are trying to use Array.find() in Redux, but it

I am currently developing a react native application and I am using basic redux for managing the state, although I am a complete beginner to this. In a specific issue, I am facing an issue while fetching data from my redux store in the edit screen where th ...