Ajax appends a single row, not an entire array

My ajax function is retrieving an array of data from the backend, but when I try to display it in the blade, only one row appears instead of multiple rows.

List of Problems

  1. Only 1 row is appended by ajax
  2. The select option is empty when the results return, even though there is no code to clear the select option.

Code Snippet

$(function() {
            // get cities
            $('#province').on('change', function(e) {
                e.preventDefault();
                $.ajaxSetup({
                    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
                });

                var hospitalId = $(this).val();

                $.ajax({
                    url: '{{ url('hospitals') }}/'+encodeURI(hospitalId),
                    dataType: "json",
                    type: 'GET',
                    success: function(data) {
                        console.log('dd: ', data.data);
                        if(data.data != null) {
                            $('.resError').hide();
                            $('.result').show();
                            // data to append
                            $.each(data.data, function(key, value) {
                                $('#code').html(value.code);
                                $('#name').html(value.name);
                                $('#type').html(value.type);
                                $('#class').html(value.class);
                                $('#beds').html(value.beds);
                                $('#owner').html(value.owner);
                                $('#province').html(value.province);
                                $('#city').html(value.city);
                                $('#address').html(value.address);
                            });
                        } else {
                            $('.resError').show();
                            $('.result').hide();
                            $('.resError').html('something went wrong, try again!');
                        }
                    },
                    error:function(err) {
                        $('.resError').show();
                        $('.resError').html('You need to select province!');
                        $('.result').hide();
                        $('#code').html('');
                        $('#name').html('');
                        $('#type').html('');
                        $('#class').html('');
                        $('#beds').html('');
                        $('#owner').html('');
                        $('#province').html('');
                        $('#city').html('');
                        $('#address').html('');
                    }
                });
            });
        });

results

https://i.stack.imgur.com/TZbpT.png

Update on Results Display

<p>Results</p>
<div class="resError clearfix mt-4" style="display:none;"></div>
<div class="result clearfix mt-4" style="display:none;">
    <table class="mb-3 table table-bordered table-hover">
        <tbody>​​​
            <tr>
                <th width="50">Code</th>
                <td id="code"></td>
            </tr>
            <tr>
                <th width="50">Name</th>
                <td id="name"></td>
            </tr>
            <tr>
                <th width="50">Type</th>
                <td id="type"></td>
            </tr>
            <tr>
                <th width="50">Class</th>
                <td id="class"></td>
            </tr>
            <tr>
                <th width="50">Beds</th>
                <td id="beds"></td>
            </tr>
            <tr>
                <th width="50">Owner</th>
                <td id="owner"></td>
            </tr>
            <tr>
                <th width="50">Province</th>
                <td id="province"></td>
            </tr>
            <tr>
                <th width="50">City</th>
                <td id="city"></td>
            </tr>
            <tr>
                <th width="50">Address</th>
                <td id="address"></td>
            </tr>
        </tbody>
    </table>
</div>

Answer №1

inside blade template

<p>Results</p>
<div class="resError clearfix mt-4" style="display:none;"></div>
<div class="result clearfix mt-4" style="display:none;">
    <table class="mb-3 table table-bordered table-hover">
        <tbody id="body">​​​
            
        </tbody>
    </table>
</div>

using javascript logic

$.each(data.data, function(key, value) {

    var element = `
    <tr>
            <th width="50">Code</th>
                <td id="code">${value.code}</td>
            </tr>
            <tr>
                <th width="50">Name</th>
                <td id="name">${value.name}</td>
            </tr>
            <tr>
                <th width="50">Type</th>
                <td id="type">${value.type}</td>
            </tr>
            <tr>
                <th width="50">Class</th>
                <td id="class">${value.class}</td>
            </tr>
            <tr>
                <th width="50">Beds</th>
                <td id="beds">${value.beds}</td>
            </tr>
            <tr>
                <th width="50">Owner</th>
                <td id="owner">${value.owner}</td>
            </tr>
            <tr>
                <th width="50">Province</th>
                <td id="province">${value.province}</td>
            </tr>
            <tr>
                <th width="50">City</th>
                <td id="city">${value.city}</td>
            </tr>
            <tr>
                <th width="50">Address</th>
                <td id="address">${value.address}</td>
            </tr>
    `;

    $('#body')append(element);

});

Answer №2

Your code snippet is currently appending values field by field based on their corresponding IDs, resulting in only the last row being displayed as each iteration updates the value in the background. To resolve this, you need to concatenate these values into a complete row and insert the entire row into the table instead of just appending each field's value individually. This way, you will be able to achieve your intended outcome by inserting rows rather than individual fields. Hope this clarifies things for you.

Answer №3

A common issue is repeatedly modifying the same elements within a table. To solve this, consider adding a new table for each row:

$.each(data.data, function(key, value) {
  $(".result").append('<table class="mb-3 table table-bordered table-hover">...</table>') 
});

For a cleaner solution, you might explore using Handlebars or another templating library to prevent generating lengthy table strings.

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

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

Utilizing AJAX/Domino Data Service API to dynamically refresh a Lotus Notes rich text field

As part of my current project, I am in charge of modernizing an older Notes application. While I would much prefer to be working on something else, this is the task at hand. According to the API, updating a rich text field should be straightforward if the ...

Extract distinct values along with their respective counts from an array containing objects

Upon receiving a JSON request containing an array of objects with two properties, the task at hand is to extract the unique values along with their respective quantities. The following JSON data is being sent through Postman: [ {"name": "First value" ...

Insert a new record into the database using Laravel-5's Eloquent ORM and a form array

I have developed a basic function that can create a new row in my database from a form submission. However, I have modified the HTML form to allow for adding multiple rows, which means the form data is now posted as an array to the function. As a result, t ...

Can you explain the distinction between a synchronous and asynchronous request in terms of their async parameter values (true/false)?

Can you explain the difference between setting async=false and async=true when utilizing the open method of the XMLHttpRequest? function GetXML() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new X ...

Best method for simultaneously calling multiple routes in Node.js and Express

What is the best approach for handling multiple routes simultaneously in Node.js and Express? For instance, if I have two routes defined as app.get('/', routes.views.index); and app.all('/header', routes.views.header); I want both route ...

Angular is sending a parameter with a null value, which is not supposed to happen

My filtering system used to work well with a code that displayed items of specific status. However, I had to modify it to match a select input requirement. <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button- ...

Employing various Class Methods based on the chosen target compiler option

Is there a way to instruct TypeScript to utilize different implementations of methods within the same class, based on the specified target option in the tsconfig.json file? I am currently transitioning one of my scripts to TypeScript to streamline managem ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Failing to clear the cache after deployment can lead to issues

I am facing a situation in my Laravel application where I need to update the code from GitHub without clearing the cache every time. Typically, I use the following command to pull the latest changes: git pull origin staging However, whenever I do this an ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...

What is the method of transferring the selected tag value to PHP using Ajax post?

I am currently facing an issue with my HTML select code. Here is the snippet: <div> <select id="pickType" class="form-control select2 " name="pickType"> <option value="" selected="selected">Select Type</option> ...

Manage the lineup of tasks in the bull queue by organizing them into groups

I am currently working on a nodejs application that handles queues using the bull library. The application is required to make multiple asynchronous HTTP requests and then process the results of these calls. I'm curious about whether bull would be an ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

What is the method for handling and replying to Ajax requests in Perl?

I am currently working on a client-side application that sends data through an AJAX POST request (request.open("POST", url, flag)) to my Perl CGI script. I need help figuring out how to extract this data using Perl and then send back some other informatio ...

Issues with the functionality of AngularJS router implementation

I have searched through various resources like Stack Overflow and other blogs, but unfortunately, I haven't been able to fix the routing issue in my AngularJS code. Although there are no error messages, the routing functionality doesn't seem to b ...

How can I display values in a combo box using ajax?

I am facing an issue with appending data to a combo box while working with 2 values in the controller. <script type='text/javascript'> $(document).ready(function(){ $('#bill').change(function(){ var bill = $(this).val ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

Is there a more efficient way to optimize my coding for this Cellular Automata project?

As a beginner in programming, I wanted to delve into the world of cellular automata and decided to create my own using JavaScript. The project involves a simple binary (black and white) 2D CA where each cell updates its color based on the colors of its 8 ...