What is the best way to extract specific values from a JSON array of objects using JavaScript?

I am facing some challenges in displaying values from the AJAX objects. My goal is to populate a select box with names using AJAX, but I seem to have made an error somewhere in my code. Can someone please assist me in identifying and correcting the mistake? Thank you in advance.

Here is my JavaScript code:

function getClient() {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var message = xmlhttp.responseText;
            var client = JSON.parse(message);
            console.log(Object.keys(client));


            document.forms["project_form"]["Project_cid"].innerHTML='<select class="form-control" maxlength="100" name="Project[cid]" id="Project_cid"><option value=Select>'+Object.keys(client)+'</option></select>'

        }
    }
    var url = "/pms_pro/index.php/client/list";
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(null);
}

When I use alert(message), it displays the following data:

[{"cid":"1","name":"suresh","address":"Chennai"},{"cid":"2","name":"Ramesh","address":"Namakkal"},{"cid":"3","name":"Vignesh","address":"Trichy"}]

Answer №1

Here is an example:

let dropdown = document.getElementById('Project_cid');

// Removing existing options
dropdown.innerHTML = '';

// Adding new options
let option, i;
for (i = 0; i < clients.length; i++) {
    option = document.createElement('option');
    option.text = clients[i].name;
    option.value = clients[i].cid;
    dropdown.add(option);
}

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

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

The autocomplete functionality with ajax is currently malfunctioning

<script> function autocomplet1() { var min_length = 0; // minimum characters to display the autocomplete var keyword = $('#select01').val(); if (keyword.length >= min_length) { $.ajax({ url: 'barcode ...

Tips for modifying the status of a single component within a v-for loop without impacting other components

I am encountering an issue with my childComponent that is dynamically rendered using v-for within the parentComponent. The Parent component contains logic to fetch data from the database and display it on the screen. The fetch request query is dependent on ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

Unable to execute specific php function using ajax

I have created a script that utilizes an ajax request. This script is triggered when a user clicks a button on the index.php page, like so: Risorse.php <form method='post'> Name <input type='text' name='nome&apo ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Tips on incorporating multiple lines of placeholder text into a textarea field:

Is it possible to add multi-line placeholder text in a textarea? I found this solution, but unfortunately it does not work on Mozilla and Safari. It seems Chrome is the only browser where this method works: $('#nameTxtBox').attr("placeholder", ...

What is the best way to trigger a function exclusively upon clicking a particular element?

My goal is to enable the user to interact with the model by positioning cubes in space upon clicking the "Cubes Mode" button. I currently have a script from the three.js website that achieves this, but I want it to only run when the mentioned button is cli ...

Is it considered acceptable to perform roughly 100 queries on the Android SQLite database for the purpose of storing a single data item?

I have recently incorporated SQLite data storage into my Android translator app. The current situation is as follows: the app receives translations in JSON format from a server, then proceeds to parse it and build an object tree consisting of 50 to 100 obj ...

Three.js: Comparing the Process of Updating Geometries with Replacing Them

In my current project, I have a complex scene filled with objects created using the ExtrudeGeometry method. These objects need to be updated every frame, with the extrusion shape and amount constantly changing. The shapes are generated using d3's voro ...

The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture. In my code, I am overriding initialization in the following way: public class HomeController: Controller { protected override void Initialize(RequestContext requestContext) ...

Getting the result from HTML5 FileReader: How does it work?

Dealing with the asynchronous nature of JS FileReader can be challenging. I need to retrieve the result after reading a file and work with that data, but I don't know when the result will be ready. How can I handle this situation effectively? $(docum ...

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

How can I read a file as JSON in Python?

I'm fairly new to python and currently working on creating, loading, and organizing a JSON file. However, I keep encountering an unusual error. Below is the code snippet I use to write the file: def save(): # function to save data to a file with ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...