Refreshing an HTML table with new data using jQuery and Ajax after a different selection

Currently, I have a piece of code that allows me to select two players and display some statistics about them. The data is presented using a regular table (image1).

The issue I am facing is that when I select a new player, instead of updating the information for the newly selected player, the table simply adds another line (image2). Although the data displayed is accurate, I do not want it to create an additional row in the table. I would prefer to replace the previous player's data with the current player's data, but I am unsure how to achieve this.

I admit that I am not very proficient in jQuery, here is my code:

<script>
        $(document).ready(function() {
//First Player Selection

            jQuery("#p1").on('focusout', function(e) {

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    }
                });
                var p1 = $('#p1').val();
                var p2 = $('#p2').val();    

                jQuery.ajax({
                    url: "{{ route('ajax') }}/?p1=" + p1 + "&p2=" + p2,
                    method: 'Get',

                    success: function(result) {

                        $("#player1").append("<h2 class='p1'>" + result[0].player + "</h2>");
                        $("#p1kills").append("<h2 class='alignRight'>" + result[0].kp + "</h2>");
                        $("#p1kda").append("<h2 class='alignRight'>" + result[0].kda + "</h2>");
                        // Additional stat updates go here...
       

                    }
                });




            });

//Second Player Selection
            jQuery("#p2").on('focusout', function(e) {

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    }
                });
                var p2 = $('#p2').val();
                var p1 = $('#p1').val();

                jQuery.ajax({
                    url: "{{ route('ajax') }}/?p1=" + p1 + "&p2=" + p2,
                    method: 'Get',

                    success: function(result) {
                        $("#player2").append("<h2 class='p1' >" + result[1].player + "</h2>");
                        $("#p2kills").append("<h2 >" + result[1].kp + "</h2>");
                        $("#p2kda").append("<h2 >" + result[1].kda + "</h2>");
                        // Additional stat updates go here...

                    }
                });




            });

        });


    </script>

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

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

Answer №1

You need to make a change here

.replaceWith()

with

.text()

I trust this resolves your issue, thank 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

Eliminate a table row in Laravel by checking the input field's value is 0 with the help of jQuery

Looking to dynamically filter a table by removing rows with number fields containing a value of '0'. Is there a way to accomplish this using jQuery? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></scri ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

Using cURL for PHP JSON parsing

I am trying to develop a basic webpage that displays the current region based on the user's IP address. To achieve this, I am utilizing an API provided by freegeoip.net. Even though I have successfully configured the code to send the user's IP to ...

Response time and execution time in Apache/PHP

Operating a web server application with Apache, PHP, and MySQL on Windows Server 2008. The server is responsible for delivering web pages and images. Lately, there has been an issue where a small percentage of users (8 out of 150) experience a high respon ...

How to fill out a multi-select dropdown in Laravel

Attempting to populate a multiple select field in Laravel has been giving me some trouble. Here's what I've tried: {{ Form::select('maisons[]', $maisons, $partenaire->maisons->pluck('id'), ['class' => &apos ...

Deleting a zip file using PHP: A step-by-step guide

After downloading the 17111611185.zip file in my project using ajax, I need to remove it from my Linux server. To achieve this, after redirecting with window.location=data, another ajax call is made to pass 17111611185.zip back to the server. $.ajax({ ...

Can someone please guide me on determining the orientation of a PDF file through PHP or a Linux script?

I am looking for a way to programmatically analyze an uploaded PDF file and identify whether the pages are in portrait or landscape orientation. Is there a method using PHP or Linux commands that can help me accomplish this task? ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Encountering a 400 error in Ajax following the execution of server-side validation by Express

I'm currently troubleshooting a form handler that consistently throws a 400 error post middleware validation. The middleware validation steps are as follows: const contactValidate = [ check('name') .exists() .trim() .escape() ...

Is there a Solution for Dealing with Floating Point Rounding Errors?

I've been working on a PHP system and encountered an issue with rounding. Upon investigating, I discovered that the problem lies within the round function in PHP. For example... Rounding 2047.615 to 2 decimal places results in 2047.62 (as expected) ...

Steps to extract date selection from a datepicker using jQuery

I recently implemented this code snippet to utilize datepicker for displaying dates: $(document).ready(function(){ $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function (selected) { var dt = new Date(selected); ...

Using Bootstrap to create a floating image amidst surrounding elements

<div id="wrapper"> <div class="row"> <div class="col-sm-6 col-xs-12 image">Image</div> <div class="col-sm-6 col-xs-12 title">Title</div> <div class="col-sm-6 col-xs-12 description"> Desc ...

Is the [] value always populated in the second DropDownList?

After populating two DropDownList in my View, I encountered an issue with the values not updating as expected: <tr> <td class="info_label">City</td> <td>@Html.DropDownListFor(m=>m.User.City,Model.City,"-- Select ...

Database numbers list with conditionals

I currently have a database structured in the following way: table: users column: day1, day2, day3, day4, day5 row: null, 1, 1, 1, null My goal is to achieve the following: if($row['day1'] == null) { $totalNullDays = '1' // &ap ...

Choosing a sequence of text snippets divided by the <br> tag found inside a specific class

Is there a way for me to extract each of those strings using jQuery or JavaScript? For example, 'fight club', 33 Main Street, Houston, etc. <span class="cart_text2"> Fight Club <br> 33 Main Street, <br> Hou ...

The image from the SQL database fails to show up in the detailsView ImageField when using the jQuery lightbox, as well as the asp:Image control

Upon clicking the image displayed in the detailsView ImageField, the jquery lightbox pops up but fails to show the picture. Instead, it displays a red x in the middle of the lightbox. The same issue arises with the asp:Image control within the provided c ...

Issues encountered when trying to refresh a form using HtmlUnit in combination with Ajax

Trying to complete and submit an HTML form using HtmlUnit, encountering issues with retrieving a select element loaded via <body onLoad="...">. The Issue: Unable to access the desired select element through methods like getSelectByName or getChildEl ...

Select preselected options in a multi-select dropdown using Knockout.js

I have a select multi that I've bound to a model, and now I want to select some values that were previously selected using a second model. It seems like a simple task, but in Knockout.js it's proving to be more complicated than expected. Here is ...

Tips for incorporating a tooltip into a disabled selectpicker option

A selectpicker I have is filled with various languages, listed as `li` tags within a `ul` tag. You can see an example in the image provided below. https://i.stack.imgur.com/dsg66.png It's noticeable that the `+ Add Language` option in the selectpick ...

guide on implementing a horizontal scrolling/swipe navbar with Cordova

Currently, I am working on creating a "category list" with multiple items for a Cordova app. The initial approach was to use a simple HTML list, but unfortunately, it seems that my list is causing some unexpected behavior. Desired swipe navbar layout: ht ...