Tips for showcasing a JSON Array in a table with AJAX on JSP

I'm relatively new to ajax and I am currently attempting to showcase data in a table within a JSP file.

The API is being called using AJAX.

The controller passes the following response:

BatchwiseStudent [name=Ram, course=MCA (Commerce), <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c49414d45406548115e4d41414d425f5b4d404d6c4b414d4540024f4341">[email protected]</a>, placed=null, batch=2016, mobileNo=7.276339096E9]

In the JSP page:

<script type="text/javascript">
        function getStudentDetails(){
            $batch = $('#batch');
            $course = $('#course');
            $.ajax({
                type: "GET",
                url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),


                    success: function(data){
                        console.log("SUCCESS ", data);

                        if(data!=null){
                            $("#batchwiseTable").find("tr:gt(0)").remove();
                            var batchwiseTable = $("#batchwiseTable");
                            $.each(JSON.parse(data),function(key,value){
                                console.log(key + ":" + value);

                                var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                                rowNew.children().eq(0).text(value['name']);
                                rowNew.children().eq(2).text(value['emailId']);
                                rowNew.children().eq(3).text(value['placed']);
                                rowNew.children().eq(4).text(value['batch']);
                                rowNew.children().eq(5).text(value['mobileNo']);
                                rowNew.appendTo(batchwiseTable);
                            });
                            $("#batchwiseTable").show();
                        }
                    },
                    error: function(e){
                        console.log("ERROR ", e);
                    }

            });

        }
    </script>

Although I can see a new row in the table, unfortunately there is no data displayed. I would like the columns to contain information such as name, email, mobile number, etc.

Could someone kindly assist me in identifying where I may have gone wrong?

Answer №1

   The following code snippet should be included in the .jsp Page to display a table without manually writing HTML code for the table:


 <div id="insert-table-here"></div>   



Javascript code:

The code below is used for making an AJAX call. Remember to replace 'uri' with the actual URL value that your application uses.


    $.ajax({
                            type: 'GET',
                            url: uri,
                            success: function (data) {
                                var str = '<table class="table table-bordered"><thead>'+
                                '<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
                                $.each(data, function (key, value) {
                                    str = str + '<tr><td>' +
                                            value.name + '</td><td>' +
                                            value.course + '</td><td>' +
                                            value.emailId + '</td><td>' +
                                            value.placed + '</td><td>' +
                                            value.batch + '</td><td>' +
                                            value.mobileNo + '</td></tr>';

                                });
                                str = str + '</tbody></table>';
                                $('#insert-table-here').html(str);

                            }, error: function (data) {

                            }, complete: function (data) {

                            }
                        });

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

Make sure to include crossorigin="anonymous" in all img tags before the images start loading

I am currently facing issues with my canvas displaying errors due to cached images causing CORS policy errors. The solution I am considering is adding crossorigin="anonymous" to all the images on my website. However, I am unsure of how to impleme ...

Ensure there is a non-null value before proceeding to add a new field

Check out the JSON input file provided below. { "data": { "no1": 12345, "cp1": { "cp1_sub1": "sub1", "cp2_sub2": "sub2" }, "cp2": null } } The ...

Struggling to make a function function properly in Node JS using Mongoose

I have been working on adding a search functionality to my application. I managed to create two functions for it, one of which works perfectly fine while the other is causing some trouble. Despite my attempts to troubleshoot the issue, I haven't had m ...

Using Nuxt.js to import custom NPM packages on a global scale

The installation process for Nuxt's plugins/modules system can be quite intricate. Despite attempting to follow various suggestions, I have struggled to accomplish a seemingly simple task. After installing the NPM package csv-parse (which can be found ...

Tips for capturing a redirect within a popup browser window?

I am currently developing a Chrome App that requires user authorization. For example, if a user wants to share a tweet on a website and clicks on a button, the app will first look for the user's access token in the Chrome storage. If the access token ...

What steps should I take to make my alert vanish?

I'm facing a challenge with an alert I created using Bootstrap in my Django project. Despite following instructions from the bootstrap website, I can't get the alert to disappear when I click on the x button. The errors I encountered are: Uncau ...

Managing table row associated javascript (control ID) when cloning the row can be achieved by properly updating the control IDs in

At first, the table only contains one tr (label/header). Upon clicking the add button, a new tr is created which will then be cloned upon subsequent clicks of the add button. <tr> <script type="text/javascript"> //fetching the value ...

PHP does not have the capability to invoke a specific object within a JSON file

I'm trying to customize my output so that only the phone number is displayed, for example "45656731" should be shown. However, when I attempt this using the code echo $result->queryResult->EntityResults->Entity->Phone;, it doesn't wor ...

Edit a Contentful article by sending a PUT request through Postman

I am currently in the process of updating a Contentful entry using Postman. Here's what I've done so far: First, I created a test post in my Contentful space to experiment with. Next, I went to Settings - API Keys - Content management tokens an ...

How come emphasizing certain characters in a string doesn't display the <b> tag in React.js?

I am trying to make a specific part of a string bold in my React.js app, but I'm not getting the expected result. Below is the code I am using and the output it produces: data?.map((item) => (<li key={item.id}>{item.title.replace(new RegExp(v ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

Is there a way to change the name of the variable when using { get; set; } in a C# class?

Recently, I came across this class: public class CheckTweetSingle { public int item1 { get; set; } public int item2 { get; set; } } After receiving a JSON string and converting the values into item1 and item2, I wondered if the ...

Designing 3D SECURE modals with Stripe.js

Currently, I am utilizing Stripe.js for managing payment forms and other authentication processes, including implementing 3D Secure. To achieve this, I am making use of the function: stripe.confirmCardPayment(clientSecret,data?,options?) I am curious to ...

Designing a Unique Shader with Three.js

Please be aware that a lot of the code has changed as per edit 3 below. I came across a blog post by Brandon Jones (link here) that I really liked. I wanted to convert his code to Three.js, but I'm encountering some difficulties. You can access his c ...

Triggering a notification from the user's end in response to server feedback

I am currently utilizing express.js on the server-side and plain JavaScript on the client-side. In the sign-up route, I aim to add a user only if they have not already signed up. If the user has already signed up, I want to display an alert message saying ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Error in Chrome: Uncaught TypeError with JQuery Ajax - Unable to access property 'data' when null

Trying to retrieve results from the YouTube API, my code is as shown below: function Vget(strt){ $.get("https://gdata.youtube.com/feeds/api/videos", { q: "soccer, 'start-index':strt, 'max-results':"5", v:"2",alt:"jsonc" }, functi ...

The curly braces in AngularJS are not resolving as expected, however, the ng-bind directive is functioning properly

I'm currently working on a Django application and utilizing AngularJS for my frontend. I have a straightforward piece of code that looks like this: <div class="vert-carousel" ng-controller="PrizeController"> <div class="gallery-cell" n ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...

Tips for achieving seamless map rotation in Mapbox

I need assistance with slowly rotating a map to a specific angle in Mapbox-gl js. I have tried two options for rotating the map, but I am struggling to achieve a slow rotation. 1. map.rotateTo() When I use map.rotateTo(angle,{duration: 2000}), I encounte ...