0

I'm creating a simple multi chat web application.i already created this system before that works well but later i made some changes in source code due to this when i enter inputs it will store the same data more than once in the database at the same time the duplicates data are incremented themselves.please anyone help me to solve this problem

this is my index page

<?php include 'db.php';?>
<!DOCTYPE html>
<html>
<head>  


<style>
   #wraper{
    height:550px;
    width:100%;
   }
   #stage{
    height:450px;
    width:100%;
    background-color:black;
    color:white;
    overflow:auto;

   }
   #pen
   {
    height:100px;
    width:100%;
    background-color:red;
   }

   </style>
  <title>forum</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
  </head> 
<body>
  <div id="wraper">
    <div id="stage">message goes here</div>
    <div id="pen">

  <br>
  <form id="image_form" method="post" enctype="multipart/form-data">
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="hidden" name="image_id" id="image_id" />
     <input type="hidden" name="user_id" id="user_id" value="<?php session_start(); echo $_SESSION['si']; ?>" />
     <input type="text"
       cols="40" 
       rows="5" 
       style="width:200px; height:50px;" 
       name="description" 
       id="description" 
       placeholder="say some thing"
       autocomplete="off" required />
       <input type="hidden" name="clock" id="clock" value="<?php echo date('Y-m-d H:i:s'); ?>" readonly="readonly" />
       <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
 </form>
 </div></div>
 </body>
 </html>
<script>  
$(document).ready(function display_msg(){
   var action = "fetch";
   $.ajax({
   url:"forum_action.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#stage').html(data);
    var objDiv = document.getElementById("stage");
        objDiv.scrollTop = objDiv.scrollHeight;
  }
  });


$('#image_form').submit(function(event){
     event.preventDefault();
     $.ajax({
     url:"forum_action.php",
     method:"POST",
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      //alert(data);
      $('#image_form')[0].reset();
      display_msg();
     }
    })
   });
  });
</script>

this is my action page

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <style>
  #container
    {
      height:70px;
      width:50%;
      color:white;

    }
    .usr_id
    {
      background-color:blue;
      height:20px;
      width:40%;
      position:relative;
      float:left;
      border-radius: 15px 0 0 0;
    }
    .msg
    {
    background-color:green;
    height:30px;
      width:100%; 
     position:relative;
      float:left;
      border-radius:0 0 15px 15px;  
    }
    .clock
    {
      background-color:purple;
      height:20px;
      width:60%;
      position:relative;
      float:left;
      border-radius:0 15px 0 0;
      text-align: right;
    }
  </style>
</head>
<body>
<?php
//action.php
if(isset($_POST["action"]))
{
 $connect = mysqli_connect("localhost", "root", "", "flash");

                                          //INSERTING MESSSA

 if($_POST["action"] == "insert")
 {
  $name=$_POST['user_id'];
  $des= $_POST['description'];
  $clock=$_POST['clock'];
  $query = "INSERT INTO forum(user_id,description,clock) VALUES ('$name','$des','$clock')";
  if(mysqli_query($connect, $query))
  {
   echo 'Data Inserted into Database';
  }

 }
                                      // FETCHING MESSAGES
  if($_POST["action"] == "fetch")
 {
  $query = "SELECT * FROM forum ORDER BY id";
  $result = mysqli_query($connect, $query);
  $output = '
   <div>
  ';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
   <div id="container">
<div class="usr_id">'.$row["user_id"].'</div>
<div class="clock">'.$row["clock"].'</div>
<div class="msg">'.$row["description"].'</div>
</div><br>
   ';
  }
  $output .= '</div>';
  echo $output;
 }


}
?>

</body>
</html>
Shanil Arjuna
  • 1,135
  • 10
  • 18
Venkat Cpr
  • 153
  • 1
  • 11
  • Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Sep 02 '18 at 12:01
  • You should make use of logging or debugging, on server-side (PHP) or client-side (javascript) or both. [Logging in php](https://stackoverflow.com/questions/3531703/how-to-log-errors-and-warnings-into-a-file), [logging in JS](https://stackoverflow.com/questions/4539253/what-is-console-log) – Alex Svetkin Sep 02 '18 at 13:38

1 Answers1

0

You're facing this problem because, and without your knowledge, you just created recursive function, which is display_msg function. To avoid that behaviour, you should put the form submit event handler outside the document.ready event handler.

// implementation of the display_msg function
function display_msg(){
   var action = "fetch";
   $.ajax({
   url:"forum_action.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#stage').html(data);
    var objDiv = document.getElementById("stage");
        objDiv.scrollTop = objDiv.scrollHeight;
  }
  }
// execute display_msg function when the document is loaded
$(document).ready(display_msg);

// attach submit event listener to #image_form
$('#image_form').submit(function(event){
     event.preventDefault();
     $.ajax({
     url:"forum_action.php",
     method:"POST",
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      //alert(data);
      $('#image_form')[0].reset();
      display_msg();
     }
    })
   });

And now it should no longer insert the same data again and again, and you should insert that script before the body closing tag to ensure that all the elements in the page are loaded and accessible.

Ps: You're mixing pure JavaScript and jQuery and that's not a wise choice, you should either use only one of them.

Hope I pushed you further.

ThS
  • 4,597
  • 2
  • 15
  • 27