Search code examples
jqueryajaxkeypress

In keypress event AJAX request is not working


I have a <textarea> and there I can type data. In keypress I have to call an ajax request. In keypress I check if the key is enter (key code = 13), then the ajax request should call.

My code is

$(document).keypress(function(e)
  { 
     var msg = $("#text").val();
     var user = $("#huname").val();
     if(e.which == 13)
    {
      $.post("chatAjax.php",{user:user,msg: msg}, function(data)
      {
         alert(data);
      });
        }
  });

And my AJAX page is

$user = $_POST['user'];
$msg = $_POST['msg'];
echo $user"<br>"$msg;

As I told if I press enter the ajax page should call, but now when I press enter still I am in the new line of <textarea>.


Solution

  • Finally, I got it. There are two problems in my code.

    1. use this

      $("textarea").keypress(function(event)

    Instead of

    $(document).keypress(function(event)
    
    1. in AJAX page I miss the concatenation (.) operator

      echo $user."
      ".$msg; /right/

    But I use this and it's wrong

    echo $user"<br>"$msg;   /*wrong*/
    

    Now it is working fine.