form Ubmit only with Enter key without button does not work

Asked

Viewed 371 times

0

Good night,

I have a little chat, in html, php and jquery, I just need to send the message form without button, but it’s just not working, someone could help me is so the code:

 <form methood='post' id="message-form">
  <textarea class="textarea" id="message_text" placeholder="Write your message"></textarea>
  </form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="sub_file/jquery-3.1.1.min.js"></script> 
<script>

  $("document").ready(function(event){

   // agora, se o formulário for enviado
    $("#right-col-container").on('submit', '#message-form' function(){
      // pega os dados da textarea
      var message_text = $("#message_text").val();
      // envia os dados para o arquivo sending_process.php
      $.post("sub_file/sending_process.php?user=<?php echo $_GET['user'];?>",
        {
            text: message_text,
        },

          //in return we'll get
          function(data, status){

             // primeiro remova o texto de
              // message_text so
             $("#message_text").val("");

             // agora adicione os dados dentro
              // o contêiner de mensagens
             document.getElementById("messages-container").innerHTML += data;
          }

        );
    });


    // se algum botão for clicado dentro
    //right-col-container
    $("#right-col-container").keyup(function(e){
          // como vamos enviar o formulário com o botão enter
        if(e.keyCode == 13){

           // então envie o formulário
          $("#message-form").submit() ; 
        }

    })


  });
</script>

my file I do the sending_process form Insert:

<?php

    session_start() ; 
    require_once("../connection.php");
    if(isset($_SESSION['username']) and isset($_GET['user'])){
         if(isset($_POST['text'])){
            //now check for empty message 
            if($_POST['text'] !=''){
            //now from here we can insert
            //data into the database

            $sender_name = $_SESSION['username'];
            $reciever_name = $_GET['user'];
            $message = $_POST['text'] ; 
            $date = date("Y-m-d h:i:sa") ;

            $q = "INSERT INTO messages 
              (sender_name, reciever_name, message_text, date_time)
              VALUES('$sender_name','$reciever_name','$message', '$date')";
              $r = mysqli_query($con, $q) ;

              if($r){
                //message sent
                 ?>

                <div class="grey-message">
                  <a href="#">Me</a> 
                  <p><?php echo $message; ?></p>

                </div>

               <?php 

              }else{
                  //problem in query
                  echo $q;
              }


            }else{
                echo 'please write something first' ;
            }


         }else{
            echo 'problem with text';
         }
    }else{

        echo 'please login or select a user to send a message';
    }


?>

2 answers

2

$("#message_text").keyup(function(e){
        if(e.keyCode == 13){
          $("#message-form").submit() ; 
        }
})
  • tried but didn’t work buddy, still no send.

  • I can see your code?

2


Creating a form without the Ubmit button is very bad (bad) for usability, you can analyze the biggest chats (Whatsapp, Telegram and etc.) all have this button.

Not to mention that you submitting the form by js through the event condition keyCode == 13, you end up losing one of the main functionalities of the textarea which is the line breaking

If you or your application do not support/wish the line break I suggest changing the field of textarea for input and create the form with the hidden Submit button, so you keep the native functionality of Submit with the button ENTER, mobile users will continue sending the form through the mobile keyboard.

Take an example:

jQuery(document).ready(function($) {
  $(document).on('submit', '#message-form', function (e) {
    // Importante para previnir o comportamente default de submit do form
    // e evitar o reload da página e possiveis duplicidades em requisições
    e.preventDefault();
    
    // debug
    alert('Form enviado com ENTER, preparando ajax.');
    
    var url = "sub_file/sending_process.php?user=<?php echo $_GET['user'];?>";
    var data = { message: $.trim($('#message_text').val()) };
    
    $.post(url, data, function (response) {
      $("#message_text").val("");

      // agora adicione os dados dentro
      // o contêiner de mensagens
      document.getElementById("messages-container").innerHTML += response;
    })
    .fail(function () {
      alert('Erro ao enviar a mensagem');
    });
  });
});
.hidden {display:none;}
input {padding: 10px 5px; width: 50%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form methood="post" id="message-form">
	<input type="text" id="message_text" placeholder="Write your message">
	<button type="submit" class="hidden">Enviar</button>
</form>

<div id="messages-container"></div>

  • Hello @Vinicius.Silva, it worked only when I click the send button, the Alert appears saying it was sent, only on the screen appears the message 'problem with text'

  • the error is coming from my sending_process file, it seems that it is not writing to the bank.. vo update the question, if you can help me thank you

  • Oops, that message is coming from else{ echo 'problem with text';} which refers to the condition if(isset($_POST['text'])){ If you notice well what my example sends by ajax to your php is { message: $.trim($('#message_text').val()) }; soon in your php will never exist $_POST['text']. You need to switch in php $_POST['text'] for $_POST['message'] or trade in js {message:... for {text:.. is at your discretion where you want to change

  • was just that.. it worked perfect.. thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.