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

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

An alternative to the JsonConstructor attribute in Json.Net for System.Text.Json

Json.Net provides the JsonConstructor attribute to direct the deserializer to use a specific constructor for object creation. Are there any equivalent features available in System.Text.Json? ...

Creating a table with React components to display an object

I'm a React novice struggling to render an object in a table. While I can access the ctx object using console.log, I can't seem to display it in the table on the browser. Any help and advice would be greatly appreciated. The code snippet is provi ...

Trouble arises with Pagination feature of Mui Data Table

Currently, I am working on a project that involves retrieving data from the CoinMarketCap API and presenting it in an MUI Data Table (specifically a StickyHeader Data Table). However, I have been encountering difficulties with changing the color of the tex ...

Why does the Setter Getter class variable in Android's RecyclerView only retrieve the last object from JSON data?

I am having an issue with my Setter Getter class variable only capturing the last object from JSON. The goal is for it to store all JSON objects in the setter getter variable so that they can be transferred to a recyclerview. Below is a snippet of the cod ...

Prevent form submission: Attempted to stop it using `e.preventDefault()` following a `$post` function, however it resulted in

I encountered an issue with my JavaScript code $('#submit').on('click', function(e) { $('#message_line').text(""); if(validate_fields_on_submit()) { e.preventDefault(); return; ...

Is it possible to format JSON data so that it can be easily read by a Google spider?

Is it possible for a Google spider to understand and interpret JSON data? Imagine having a JSON feed that holds information for an e-commerce website. This JSON data is used to populate a page that can be read by users in their browser. (Essentially, the ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Changing JSON format into a DataTable using C#

Currently, I am attempting to transform a JSON string into a DataTable within WEBAPI The structure of the JSON string is as follows: [ [ "Test123", "TestHub", "TestVersion", "TestMKT", "TestCAP", ... ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

Troubleshooting the lack of updates in a partial view with MS AJAX in ASP.NET MVC

I've implemented a search text box and a button that is meant to display the search results in a partial view using ajax when the button is clicked. Even though I can see data when setting a breakpoint in the partial view, nothing appears on the form. ...

The AWS API Gateway quickly times out when utilizing child_process within Lambda functions

I'm encountering an issue with my Lambda function being called through API Gateway. Whenever the Lambda triggers a spawn call on a child_process object, the API Gateway immediately returns a 504 timeout error. Despite having set the API gateway timeou ...

Ways to detect when the window printing process has been completed

Within my application, I attempted to generate a voucher page for the user using the following code: var htm ="<div>Voucher Details</div>"; $('#divprint').html(htm); window.setTimeout('window.print()',2000); The &apo ...

How can you trigger a link click event when clicking anywhere on the page using Jquery?

Here's the code I'm working with: <a href="http://google.com" target="_blank">Open in new tab </a> I am trying to make it so that when a user clicks anywhere on the website, the link above will be automatically clicked and a new tab ...

Splunk may not extract all field values from lengthy JSON files

My challenge lies in successfully ingesting lengthy JSON files into my Splunk index. Each record is capable of containing over 10000 characters, leading to potential truncation issues. To tackle this problem, I implemented a TRUNCATE=0 directive within the ...

Manipulating data with Angular's array object

I am having an issue with posting an object array. I anticipate the post to be in JSON format like this: {"campaign":"ben", "slots":[ { "base_image": "base64 code here" } ] } However, when I attempt to post ...