The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop.

Although the table refreshes correctly and adds new values from the database, the onclick function stops working when I click on table elements. However, if I manually refresh the table, it starts working again but still only once.

I'm not sure what I'm doing wrong here. Can someone help?

Below is my onclick function along with the Ajax code:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

    $(document).ready(function(){
        $('#main tbody').on('click', 'td', function () {
            $irow = $(this).parent().index(); 
            $icol = $(this).index();
        console.log(" row and column: ");//to debug
        console.log($irow);//to debug
        console.log($icol);//to debug
        $.ajax({ 
           type: "POST", 
           url: "check_db.php", 
           data: { 'srow' : $irow,
               'scol' : $icol
               }, 
           success: function(data) {
                  alert(data);
                  console.log(data);
                  $("#view").load(" #view > *")
                  } 
                  }); 
        });
        });

 </script>
 
<style>
table, th, td {
  border: 1px solid black;
}
</style>
</head>

And here is the code inside the main div:


<body>
<h1>Welcome <?php echo $_SESSION["username"] ?> </h1>


<div id="view">

<?php
$sql = "SELECT username, row, col FROM seats";
$result = $link->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $outer_array[]=$row;//FILLING OUTER_ARRAY EACH ROW AS SEPARATE ARRAY.
      //  echo "<br>"."username: " . $row["username"]. " - row: " . $row["row"]. " col: " . $row["col"]. "<br>";
    }
}else{
    echo "0 results";
}
//======================Loop to create table starts from here!!!=================================
$nrows= 9; // Number of rows in table
$counter_row=0;//counter to use inside loop to match desired row value
$ncols=6;// Number of columns in table
$counter_col=0;//counter to use inside loop to match desired column value
echo '<table id = "main" style="width:100%"><tbody>';
for ($row = 0;$row<$nrows;$row++) {
    echo "<tr>";
    for ($col = 0;$col<$ncols;$col++) {
        for ($i = 0;$i<count($outer_array);$i++) {
                if (($outer_array[$i]['row']==$counter_row)&&($outer_array[$i]['col']==$counter_col)){
                    $uname = $outer_array[$i]['username'];
                    break;
                } else {$uname = "free";} 
        }
        if ($uname=="free"){
            echo "<td style='background-color:green;color:black'> </td>"; 
        }elseif($uname!= $_SESSION["username"]) 
        { echo "<td style='background-color:yellow;color:black'>$uname</td>";
        } else echo "<td style='background-color:orange;color:black'>$uname</td>";
        $counter_col++;
        if($counter_col==$ncols){$counter_col=0;}
    }
    echo "</tr>";
    $counter_row++;
}
echo '</tbody>';
echo '</table>';
?>
</div>


Answer №1

Try utilizing the primary fixed element (#container in this instance) as your Event Supervisor:

$('#container').on('click', 'span', function () {

To elaborate, when an AJAX request is successful and you reconstruct the whole content of your unchanging #container, the TBODY within $('#table tbody') becomes a brand new component that no longer registers the original click events.

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

The nightwatch.js script is halting operations once the test suite has been completed

Recently, I've implemented functional test automation using nightwatch.js. However, I encountered an issue where the test pauses after the test suite is completed, failing to end the process. Below is a snippet of the code: var afterSuite = function( ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...

Hide or show list items in an unordered list using jQuery

I am interested in creating a script that can toggle between "show more" and "show less" functionality for elements in a list. I came across this script: HTML <ul id="myList"> <li>One</li> <li>Two</li> <li> ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

Stop all AJAX calls and timers immediately

I need to terminate an ajax request along with its timer that is being executed within a function: var run_timer; var run; function myrequest() { if(run && run.readystate != 4){ run.abort(); } run = $.ajax({ type:"POST", ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Encountering PHP encoding problems while utilizing http_request2

I've been attempting to make a request to a website using the HTTP_REQUEST2 package. My try catch statement is as follows: try { return $this->_HttpObject->send();//->getBody(); } catch (Exception $exc) { echo $exc-> ...

I am working on a NodeJs code that utilizes (Array)Buffers and native readUInt16BE. However, since I am working within a browser context, I plan to opt for DataView.getUint16 instead

While working on adapting a JPEG parsing function in Node.js for use in a browser environment, I discovered that the original code can be found here. The challenge lies in using Node.js' Buffer class. To make it compatible with a browser environment, ...

Incorporating a recurring image beneath a navigation menu

I'm attempting to recreate a header that has a similar appearance to the following: https://i.stack.imgur.com/uVXs3.png However, I am facing challenges in generating the repeating diamond design beneath the black bar. The diamond pattern resembles t ...

Troubleshooting npm audit error involving loadVirtual and ENOLOCK

➜ npm safety check npm ERR! code ENOLOCK npm ERR! safety check This operation requires an existing lockfile. npm ERR! safety check Please generate one using: npm i --package-lock-only npm ERR! safety check Original error: loadVirtual needs a preexistin ...

loop through the links using their unique identifiers

Here is my current code in Jade/Pug: #pm_language.dropdown(aria-haspopup='true', aria-expanded='false') button#langbutton.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown') Lang [RU] ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

How to Target a Specific Element Using its Class with jQuery

Hey there! I'm currently working with the following snippet of HTML code: <li class="grey"> <div class="row"> <button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button> </div ...

How can eslint be used to enforce a particular named export?

Is there a way to use eslint to make it mandatory for JavaScript/TypeScript files to have a named export of a specific name? For instance, in the src/pages folder, I want all files to necessitate an export named config: Example of incorrect usage src/page ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

Creating a responsive carousel that is not yet designed

As a beginner, I'm facing what seems like a simple problem that I just can't solve. Here is the HTML code I've written: <div class="discs container"> <ul> <li><div class="arrowleft"><a href="#" >< ...

Tips for integrating DataTables selection filtering functionality

Here's a snapshot of my screen I'm attempting to utilize data tables This is what I have on the main page $('#student-listing-table').dataTable(); $('#student-listing-table').find('label').html('Search By Nam ...

Can you please elaborate on the concept of type coercion in JavaScript?

I've come across information stating that when comparing an object with a number, type-coercion occurs. ToPrimitive is called on the object which then invokes valueOf and, if necessary, toString. However, I'm struggling to understand how this pro ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...