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

Load data asynchronously using a promise in select2

Is there a way to load options for select2 asynchronously without using ajax requests? I want to retrieve values from a promise object instead. Currently, my code loads data in the query function, but this means that it queries the data with every keystrok ...

Techniques for implementing a PHP base_url() function in a JavaScript file

I need to pass base_url from the Book Controller to the book.js file This is the function within book.js function loadPage(page, pageElement) { // Create an image element var img = $('<img />'); img.mousedown(function(e) { ...

What is the best way to retrieve a Promise from a store.dispatch within Redux-saga in order to wait for it to resolve before rendering in SSR?

I have been experimenting with React SSR using Redux and Redux-saga. While I have managed to get the Client Rendering to work, the server store does not seem to receive the data or wait for the data before rendering the HTML. server.js ...

Converting Moment JS to Carbon for Time Calculations

How can I synchronize the timestamps between MomentJS and Carbon instances in the GMT timezone? $(document).on('click', '#confirm-reservation .dropdown-menu a', function () { $('#insert_text').text($(this).text()); va ...

What mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

Merging distinct objects/values in AngularJS/Javascript to create a straightforward list

I possess a dynamically generated, multi-level nested object containing DISTINCT values. My goal is to flatten it (using either AngularJS or vanilla JS) and produce a straightforward array or object for each key/value pair. For example, if the object takes ...

Different color for background of division

I am working with a structure that looks like this: <div class="wrapper"...> <a href="#"...>blah</a> <div class="post"...>stuff</div> </div> This structure repeats multiple times on a dynamic page. I am looking f ...

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Managing multiple JQuery Dialog boxes can be tricky, especially when you can only close one instance at a time

I'm currently working on integrating multiple instances of Jquery's Dialog box on the same website. The issue I'm facing is that I have two instances that I initialize using a new function like this: function Modal(param) { this.modal = ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

How can I obtain the coordinates when the mouse enters Vue?

Trying to create an animation triggered by the mouseenter event in Vue, I ran into a roadblock - obtaining the coordinates of the sections. <script setup> function fetchCoordinates(e) { const coords = { x: e.clientX, y: e.clientY } // This seems to ...

Unraveling Complex JSON Structures in React

Having trouble reading nested JSON data from a places API URL call? Look no further! I've encountered issues trying to access all the information and nothing seems to be coming through in the console. While unnested JSON is not an issue, nested JSON p ...

Enhancing React Native experience by dynamically editing array elements

This code block defines the state of my program, including an array: this.state = { arr: [{ arrid: 0, arrEmail: '', arrName: '', arrPhone: '' }], id: 0, email: "", isChecked: true, name: "", phon ...

Tips for overlaying text onto a canvas background image

I'm curious about how to overlay text on top of an image that is within a canvas element. The image is a crucial part of my game (Breakout), so it must remain in the canvas. I've tried adding text, but it always ends up behind the image, which is ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...

Submitting a PHP form by uploading an image with AJAX

I'm looking to submit form data to a MySQL database using AJAX. While I'm not very familiar with AJAX, I managed to write a code that successfully submits text data to the database. However, I'm facing issues with uploading and storing image ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Incorporate Ruby's embedded helpers with jQuery for advanced functionality

How do I properly add a ruby helper to iterate through an active record response? I attempted to do so with the following code (.html or .append): $( ".result" ).html('<%= @products.each do |product| %><label>product</label><% e ...

What is the process for securing a photo to a canvas?

I have included <input type='file' id="image"> in my HTML code. How can I display the uploaded image on my canvas using p5.js? What is the best way to add an event listener to this action and transfer the uploaded file onto the ca ...