Guide on how to retrieve information from an API and populate it into a dropdown menu

Currently, I am developing an MVC application that interacts with an API. My goal is to call a specific method from the API in order to populate data into a combo-box. However, as a newcomer to this technology, I am unsure of the best approach to take.

Any guidance or suggestions would be greatly appreciated.

The ClaimController within the API contains the necessary function for this task.

[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
    try
    {

        using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
        {
            Request.Headers.Clear();
            var tmpresults = logic.GetScheme();
            var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
            var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
    }
}

In terms of the client-side views and UI, I aim to invoke the API function to populate the data into the combo-box.

function GetAllScheme() {
    var select = $("#ddlScheme");

    $.ajax({

        type: "GET",
        url: "http://localhost:55393/_Api/Claim",

        dataType: "json",
        success: function (data) {
            debugger;
            var datavalue = data;
            var serverResponse = datavalue;
            contentType: "application/json";
            $.each(serverResponse, function (i, serverResponse)
            {
                select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")

            });

        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
}

Dropdown

<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
                                                                 <select 
                                                                </select>
                                                            </div>

Answer №1

After receiving a response from the server, make sure to dynamically add option elements to your select (dropdown) element. Here is an example of how you can achieve this:


function PopulateDropdown() {
    // Identify the dropdown by its ID
    var dropdown = $("#myDropdown");

    $.ajax({
        ...
        success: function(data) {
            $.each(data.results, function(index, item) {
                $("#resultTable").append('<tr><td>' + item.name + '</td></tr>');
                
                // Add each item as an option in the dropdown
                dropdown.append('<option>' + item.name + '</option>');
            });
        },
        ...
    });
}

For a working example, refer to this demo on jsfiddle https://jsfiddle.net/y8nwks1b/

Answer №2

If you're using Chrome, go into the developer tools and observe how the server responds. After the server has responded, set a breakpoint because maybe there is an issue with the code.

function FetchAllData() {
      $.ajax({
        type: "GET",
        url: "http://localhost:32359/api/Claim",

        dataType: "json",
        success: function(data) {
          $.each(data.responseJSON, function(index, item) {
            $("#DataTbl").append('<tr><td width="50px">' + item.Description +
              '</td></tr>');
          });

        },
        error: function(xhr) {
          alert(xhr.responseText);
        }
      });

    }

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

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Numerous references embedded within a Vue.js component

I am currently working with multiple instances of a polygonCrop component in Vue.js, each one having a unique reference to a canvas property. These components are utilized in separate crop functions triggered by button clicks. My question is how to effecti ...

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Jquery on method triggers a single event only

I am encountering an issue with adding and removing a class from an element using the on() method to handle click events. The code works fine on the first click, but subsequent clicks do not trigger the event anymore. Here is the code snippet: $(&apo ...

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Issues with Loading Bootstrap JavaScript on Basic "Hello World" Project

I am experiencing an issue where the JavaScript code is not displaying on my website. I have checked the inspect element sources and it seems to load correctly, but for some reason, it is not being applied. Any insights on why this might be happening? Than ...

Wordpress fails to produce results when using Ajax and Jquery

I have encountered an issue with my code. It works perfectly fine outside of WordPress, but when I try to integrate it into a WordPress environment, the Ajax part fails consistently. Below is how I include jQuery and Ajax in WordPress: function transtatus ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

Best practices for retrieving a PHP variable without the need to submit a form using AJAX

I'm a beginner with AJAX I'm trying to achieve something similar to this: $query="select name from login_master where name=txtName.value();"; //txtName refers to a textbox. Is it possible to accomplish this using AJAX without submitting the fo ...