Search code examples
javascriptphpjqueryxmlhttprequestajaxform

Bypass the loading function on PHP generated table when Ajax post request is triggered


I am trying to do Ajax post request without refreshing page in loading php generated table. PHP table is loading without refreshing the page by using XMLHttprequest onload(). The post request is triggered by using onclick button and it is within the php generated table, and then the request is processed via Ajax form data serialize. The result is done successfully, but it needed to do double click to override loading function and process the Ajax post request. Thus, I come here to ask a question that can I finish the process within single click.

This is my whole code:

 <?php
require_once "db_conn.php";

$Host_ID = $_GET['Host_ID'];
$sql = "Select * from Chat_List inner join Chat_Room on Chat_List.Room_ID = Chat_Room. Room_ID 
        where Chat_List.Chat_ID = $Host_ID order By Chat_Room.Update_time DESC";
$row = mysqli_query($conn, $sql);

?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="Chat_Search.css">
</head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
 
function ChatRoomSearch(){
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function(e){
    document.getElementById("table3").innerHTML = this.responseText;
    //document.getElementById("Check").trigger("Click");
  }

  xhttp.open("GET", "Chat_Search.php?Host_ID="+Host_ID, true);
  xhttp.send();
}
setInterval(function(){
     ChatRoomSearch(); 
  }, 3000);


</script>
<body>
<?php
$Host_ID = $_GET['Host_ID'];
echo"<script> var Host_ID = '$Host_ID';</script>";
?>

<table id = 'table3' border = 1 cellpadding = 10>
<tr>
<th>ID</th>
<th>Friend</th>
<th>Message</th>
<th>Room ID</th>
<th>Action</th>
</tr>
<?php foreach($row as $row):
?>
<tr>
<td><?php 
    if ($row["Invitor"] != $Host_ID){
        echo $row["Invitor"];
    }else{
        echo $row["Host"];
    }
?></td>
<td><?php echo $row["Room_Message"]; ?></td>
<td><?php echo $row["Room_ID"]; ?></td>
<td>
  <?php
  if ($row["status"] == 'confirm' and $row["Invitor"] == $Host_ID){
  ?>
<form id = "form<?php echo $row["Room_ID"]; ?>" action="Chat_Room_Confirm.php">
  <input type="text" name="Room_ID" id="Room_ID<?php echo $row["Room_ID"]; ?>" value="<?php echo $row["Room_ID"]; ?>">
  <input type="text" name="Room_status" id="Room_status<?php echo $row["Room_ID"]; ?>" value="Chat">
  <input type="button" class="myinput" id="myinput<?php echo $row["Room_ID"]; ?>" value="Invite" >
  <script>
$(document).on('click', function(event){
    event.preventDefault();
   $('#myinput<?php echo $row["Room_ID"]; ?>').on ('click' ,function(){
      var form = $('#form<?php echo $row["Room_ID"]; ?>');
      var Room_ID = $('#Room_ID<?php echo $row["Room_ID"]; ?>').val();
      var Room_status = $('#Room_status<?php echo $row["Room_ID"]; ?>').val();
      var formData = form.serialize();
      $.ajax({
         url:form.attr("action"),
         method:"POST",
         data:formData,
         cache:false,
         success:function(){
           alert('Data Send');
         }
      });
   });
   return false;
});
  </script>
</form>
  <?php } ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

I have tried the below the code, but it doesn't work.

$(document).ready(function(){
   $('#myinput<?php echo $row["Room_ID"]; ?>').on ('click' ,function(event){
      event.preventDefault();      
      var form = $('#form<?php echo $row["Room_ID"]; ?>');
      var Room_ID = $('#Room_ID<?php echo $row["Room_ID"]; ?>').val();
      var Room_status = $('#Room_status<?php echo $row["Room_ID"]; ?>').val();
      var formData = form.serialize();
      $.ajax({
         url:form.attr("action"),
         method:"POST",
         data:formData,
         cache:false,
         success:function(){
           alert('Data Send');
         }
      });
   });
   return false;
});

Thank you for everyone looking my question.


Solution

  • A lot of improvement is required in your code.

    a) Your script is open to SQL Injection Attack. Even if you are escaping inputs, it's not safe! You should always use prepared parameterized statements in either the MYSQLI_ or PDO API instead of concatenating user-provided values into the query.

    b) jQuery code for the same event handling inside the loop is a blunder, don't do that.

    c) Until you get Host_ID in $_GET, don't execute your code.

    Here is a sample code:

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="Chat_Search.css">
    </head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <body>
            <?php 
            require_once "db_conn.php";
            $Host_ID = 0;
            if(!empty($_GET['Host_ID'])){
    
                $Host_ID = $_GET['Host_ID'];
                $stmt = mysqli_prepare($conn, "Select * from Chat_List inner join Chat_Room on Chat_List.Room_ID = Chat_Room. Room_ID 
                        where Chat_List.Chat_ID = ? order By Chat_Room.Update_time DESC");
                mysqli_stmt_bind_param($stmt, "i", $Host_ID);
                mysqli_stmt_execute($stmt);
                $result = $stmt->get_result();
    
            ?>
            <table id = 'table3' border = 1 cellpadding = 10>
                <tr>
                    <th>ID</th>
                    <th>Friend</th>
                    <th>Message</th>
                    <th>Room ID</th>
                    <th>Action</th>
                </tr>
                <?php while ($row = $result->fetch_assoc()) {?>
                    <tr>
                        <td>
                            <?php if ($row["Invitor"] != $Host_ID){
                                    echo $row["Invitor"];
                                }else{
                                    echo $row["Host"];
                                }
                            ?>
                        </td>
                        <td><?php echo $row["Room_Message"]; ?></td>
                        <td><?php echo $row["Room_ID"]; ?></td>
                        <td>
                            <?php if ($row["status"] == 'confirm' and $row["Invitor"] == $Host_ID){?>
                                <form id = "form<?php echo $row["Room_ID"]; ?>" action="Chat_Room_Confirm.php">
                                    <input type="text" name="Room_ID" id="Room_ID<?php echo $row["Room_ID"]; ?>" value="<?php echo $row["Room_ID"]; ?>">
                                    <input type="text" name="Room_status" id="Room_status<?php echo $row["Room_ID"]; ?>" value="Chat">
                                    <input type="button" class="myinput" id="myinput<?php echo $row["Room_ID"]; ?>" value="Invite" >
                                </form>
                            <?php } ?>
                        </td>
                    </tr>
                <?php } ?>
            </table>
            <?php } ?>
        </body>
    </html>
    <script>
    var Host_ID = "<?php echo $Host_ID;?>";
    function ChatRoomSearch(){
        if(Host_ID > 0){
            const xhttp = new XMLHttpRequest();
            xhttp.onload = function(e){
                document.getElementById("table3").innerHTML = this.responseText;
            }
    
            xhttp.open("GET", "Chat_Search.php?Host_ID="+Host_ID, true);
            xhttp.send();
        }
    }
    
    $(document).ready(function(){
        setInterval(function(){
            ChatRoomSearch(); 
        }, 3000);
    
        $(document).on('click', '.myinput', function (event) {
            event.preventDefault();
            var formData = $(this).closest('form').serialize();
            $.ajax({
                url: $(this).closest('form').attr("action"),
                method: "POST",
                data: formData,
                cache: false,
                success: function () {
                    alert('Data Send');
                }
            });
        });
    });
    </script>