-1

I'm trying to submit a message to database by using a form, and I want that form to be submitted without refreshing.

I used Javascript Code for catching data from the form "JS" Code, coded in the same page of the form.

 $(document).ready(function(){  
      $('#submit').click(function(){  
           var typed_msg = $('#typed_msg').val();   
           if(typed_msg == '')  
           {  
                $('#error_msg').html("Message blank!");  
           }  
           else  
           {  
                $('#error_msg').html('');  
                console.log(typed_msg);
                $.ajax({  
                     url:"msg.php",  
                     method:'post',  
                     data:{typed_msg:typed_msg},  
                     success:function(data){  
                          $("form").trigger("reset");  
                          $('#succ_msg').fadeIn().html(data);  
                          setTimeout(function(){  
                               $('#success_message').fadeOut("Slow");  
                          }, 2000);  
                     }  
                });  
           }  
      });  
 });  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" style="padding:5px 0">
       <input autofocus autocomplete="off" name="typed_msg" id="typed_msg" >
       <input type="button" name="submit" id="submit" value="Go" class="btn btn-success" >
    </form>

PHP file I used to submit data to the database, "msg.php"

<?php
require_once('db.php');

 if(isset($_POST["typed_msg"]))  
 {  
      $typed_msg = mysqli_real_escape_string($con, $_POST["typed_msg"]); 
      $sql = "INSERT INTO messages (`time_send`,`sender_id`,`receiver_id`,`msg_body`) VALUES (now(),'".$_SESSION['id']."','$msgId','$typed_msg')";  
      if(mysqli_query($con, $sql))  
      {  
           echo "Message Saved";  
      }  
 } 


?>
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Junc Book
  • 21
  • 6
  • Nothing happens with clicking a submit button, even no movement. – Junc Book Feb 04 '20 at 07:31
  • you had already prevent the form when submit button is clicked ? – Qonvex620 Feb 04 '20 at 07:36
  • no event when you clicked submit button ? – Qonvex620 Feb 04 '20 at 07:41
  • I didn't prevent the form, but just by hitting enter button. – Junc Book Feb 04 '20 at 07:46
  • Your code is vulnerable to SQL injection. You should use prepared statements. – Dharman Feb 04 '20 at 07:46
  • and no event happens when clicking the GO button. – Junc Book Feb 04 '20 at 07:47
  • try to put a e.preventDefault() to it – Qonvex620 Feb 04 '20 at 07:48
  • When you're having trouble, try to [reduce the problem to the simplest possible thing that reproduces the problem](https://stackoverflow.com/help/mcve). You say nothing happens when you click the button - [here's a much simplified JSFiddle of your code](https://jsfiddle.net/dont_panic/f2e1xtmo/) that shows something does happen, your JS is triggered fine. Do the same in your JS - does it work? If yes, move to the next step - check your devtools, is the POST actually sent? – Don't Panic Feb 04 '20 at 09:18
  • you just don't start the session in the php file. So the query will fail since you don't have the value of the sender_id. – Lelio Faieta Feb 04 '20 at 11:36

4 Answers4

2

Use this code

HTML form

<form action="" method="POST" style="padding:5px 0">
   <input autofocus autocomplete="off" name="typed_msg" id="typed_msg" >
   <input type="button" name="submit" id="submit" value="Go" class="btn btn-success" >
</form>

Script

 $(document).ready(function(){  
      $('#submit').click(function(){          
           var typed_msg = $('#typed_msg').val();   
           if(typed_msg == '')  
           {  
                $('#error_msg').html("Message blank!");  
           }  
           else  
           {  
                $('#error_msg').html('');  
                $.ajax({  
                     url:"msg.php",  
                     method:'post',  
                     data:{'typed_msg':typed_msg},  
                     success:function(data){  
                          $("form").trigger("reset");  
                          $('#succ_msg').fadeIn().html(data);  
                          setTimeout(function(){  
                               $('#success_message').fadeOut("Slow");  
                          }, 2000);  
                     }  
                });  
           }  
      });  
 });
Rahul Koshti
  • 186
  • 1
  • 10
0

You have to use event.preventDefault() to prevent hapening default action.

  1. Using forms onsubmit event
<form action="" onsubmit="formSubmitted" method="POST" style="padding:5px 0">
   <input autofocus autocomplete="off" name="typed_msg" id="typed_msg" >
   <input type="button" name="submit" id="submit" value="Go" class="btn btn-success" >
</form>
  1. Using onclick event.
<form action="" method="POST" style="padding:5px 0">
   <input autofocus autocomplete="off" name="typed_msg" id="typed_msg" >
   <input type="button" name="submit" onclick="formSubmitted" id="submit" value="Go" class="btn btn-success" >
</form>
<script>
    function formSubmitted(e){  
        e.preventDefault();
       var typed_msg = $('#typed_msg').val();   
       if(typed_msg == '')  
       {  
            $('#error_msg').html("Message blank!");  
       }  
       else  
       {  
            $('#error_msg').html('');  
            $.ajax({  
                 url:"msg.php",  
                 method:'post',  
                 data:{typed_msg:typed_msg},  
                 success:function(data){  
                      $("form").trigger("reset");  
                      $('#succ_msg').fadeIn().html(data);  
                      setTimeout(function(){  
                           $('#success_message').fadeOut("Slow");  
                      }, 2000);  
                 }  
            });  
       }  
    }
</script>
Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
0

Html :

<form action="" method="POST" id="submit" style="padding:5px 0">
   <input autofocus autocomplete="off" name="typed_msg" id="typed_msg" >
   <input type="submit" name="submit"  value="Go" class="btn btn-success" >
</form>

Script Submission :

$('#submit').submit(function(e){ 
       e.preventDefault();         
       var typed_msg = $('#typed_msg').val();   
       if(typed_msg == '')  
       {  
            $('#error_msg').html("Message blank!");  
       }  
       else  
       {  
            $('#error_msg').html('');  
            $.ajax({  
                 url:"msg.php",  
                 method:'post',  
                 data:{typed_msg:typed_msg},  
                 success:function(data){  
                      $("form").trigger("reset");  
                      $('#succ_msg').fadeIn().html(data);  
                      setTimeout(function(){  
                           $('#success_message').fadeOut("Slow");  
                      }, 2000);  
                 }  
            });  
       }  
  }); 
Ripon Uddin
  • 709
  • 3
  • 14
  • 29
-1
 $sql = "INSERT INTO messages (`time_send`,`sender_id`,`receiver_id`,`msg_body`) VALUES (now(),'".$_SESSION['id']."','$msgId','$typed_msg')";

where is this $msgId come from?


please check this link to check ajax error: jQuery ajax error function

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Sandeep
  • 47
  • 4