Using Ajax to insert information into a row of a table

I am looking to update a table with data from a JavaScript function. The table is located in the same .jsp file but not inside the script.

Using AJAX

<script type="text/javascript">
        function searchDetails() {

            $.ajax({
                type : "post",
                data : {
                    'accountNo' : $(accNumber).val()
                },
                url : "/banking-internet/account-history/add",
                cache : false,
                success : function(data) {
                    var transactionList = data;
                },
                error : function(e) {
                    alert('Error: ' + e);
                }
            });

        }
    </script>

Table Structure

             <tr>
                <th>Transaction Type</th>
                <th>Amount</th>
                <th class="hide-on-mobile">Description</th>
            </tr>
            <c:forEach var="transaction" items="${transactionList}">
                <tr>
                    <td>${transaction.transactionDate}</td>
                    <td>${transaction.transactionType}</td>                     
                    <td>${transaction.accountNarration}</td>
                </tr>
            </c:forEach>

The values are being passed correctly to the data. However, I am facing issues accessing the value outside of the script for further use.

success : function(data) {
                        var transactionList = data;
                    },

This segment successfully retrieves the value from the controller.

Seeking assistance, please.

Answer №1

To enhance your table, consider assigning an ID as shown below:

    <table id="updated_table">

Next, use the following function:

    success : function(info) {
                    var dataList = info;
                    addRow ("updated_table", dataList);
    },

Then replace cellX.innerHtml = data.whatever_member_object;

    <script language="javascript">
    function addRow(tableID, dataList) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        cell1.innerHtml = dataList;

        var cell2 = row.insertCell(1);
        cell2.innerHTML = dataList;

        var cell3 = row.insertCell(2);
        cell3.innerHTML = dataList;             
    }
    </script>

We hope this solution proves effective for you.

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

Whenever I run "npm run build-dev" in Webpack with JavaScript, the browser continuously refreshes

I've been working on familiarizing myself with webpack lately. I've managed to convert everything to load modules and plugins, and it's all working fine when I use "npm run build-prod". Even when I use liveServer, the HTML loads properly. Ho ...

Combining Json, Jquery Autocomplete, and PHP to customize the displayed search options based on multiple items within the Json data

I have a PHP file that returns an array of results, with the 'Name' field being one of them. I want to customize my jQuery autocomplete feature to only search by the 'Name' field and suggest results based on that. However, once a sugges ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

Generate a new nested div if there is already a different child present at the specified coordinates (x, y)

My goal is to add a textarea to a sidebar on the right whenever a click is made on the page. The current code I have is as follows: $('#page_to_be_clicked').click(function(e){ var offset = $(this).offset(); var comment_box_y_coord = e.pa ...

What is the best method for transforming a JavaScript array of Objects to a different format?

Is there a way to transform this array of objects from one format to another? The original array is as follows: const data = [ {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}}, {name: 'Customer 2', value: {Oil: ...

having trouble retrieving information from the input field

I'm having trouble retrieving the user's input from the input field, can someone assist me with this issue? I can't seem to identify what the problem is here. var ftemp = document.getElementById("Farenheit").value; <td> <i ...

Verifying Username Availability with Struts2 and AJAX Request

Currently constructing a web application utilizing Struts2 as the primary framework. The main focus is to verify the availability of a username through an AJAX call (open to alternative approaches if there are simpler methods to achieve the same outcome.) ...

Tips for arranging alternating elements in a column layout using an array data model

In the $scope there is a dynamic array and in the HTML template, there are three columns. The goal is to render elements from the array in the HTML like this: <div class="first-column"> <div><!--element of (index + 3) % 3 === 0 will be pl ...

Different methods to avoid using $scope.$watch in a directive when dealing with an undefined variable

As I work on my angularjs application, I find myself utilizing directives for reusable UI elements across different pages. However, I encounter a challenge when a directive depends on a value from a promise. In such cases, I have to employ $scope.$watch al ...

Tips for recognizing when AJAX content, such as images and text, has been fully loaded within a div while utilizing both AJAX and jQuery

$.ajax({ type: 'POST', url: 'show-photo3.php', data: 'type='+type+'&count='+count+'&aid='+aid, dataType: 'html', success: function(response) { //alert(response ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

I'm encountering inexplicable duplications of elements on my Wordpress site

Here is an example of my template header: <header> <?php if ( function_exists( 'jetpack_the_site_logo' ) ) jetpack_the_site_logo(); ?> <a class="menu-toggle">menu</div> <?php wp_nav_menu( array('them ...

Steps to Turn Off Automatic Loading in Jquery Ajax tabs

I've encountered an issue with auto-loading in jQuery Ajax tabs. It's causing my browser to hang up. I need to find a way to disable the auto-loading feature. Here's the scenario of what I need: On the first tab, it loads the following cate ...

Using Ajax and PHP to upload an image

I'm looking to implement an image upload feature triggered by a button click with the id of #myid.save. Below is the code I have so far: HTML Code: <canvas id="cnv" width="500" height="100"></canvas> <input id="myid_save" type="submit ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Using Next.js to implement a timeout feature that pauses using a React state

Below is the code for my component, which is called on a page with <DetectPitch />: import { useEffect, useState } from 'react'; export default function DetectPitch() { const [detect, setDetect] = useState(false); useEffect(() => ...

What could be causing the inconsistency in the success rate of my Get request, with it working occasionally but returning a

Why is it that my Get request works on occasion, but most of the time it returns a 404 error? I've been experimenting by removing the "next()" function, but it doesn't make a difference. I've also tried placing "res.json(req.user.firstName) ...

Launch in a new window using JavaScript

Check out my interactive map here. Currently, when I click on different sections of the map, the target page opens in the same window. However, I would like it to open in a new window instead. <iframe src="http://bluewingholidays.com/map/map.html ...