3

The function newMessage() is only called when the user presses the submit button or presses enter. The problem is that the AJAX script keeps calling inside, even when newMessage() is not called. For example if I type anything on the input field without even hitting the submit, the value would be passed by AJAX.

I can't seem to understand how to stop this, any help would be appreciated. Thank you.

<div class="message-input">
  <div class="wrap">
    <input type="text" name="msg" id="msg" placeholder="Write your message..." />
    <i class="fa fa-paperclip attachment" aria-hidden="true"></i>
    <input type="hidden" value="0" name="convo_id" id="convo_id" readonly/>
    <button class="submit">
      <i class="fa fa-paper-plane" aria-hidden="true"></i>
    </button>
  </div>
</div>
function newMessage() {
  message = $(".message-input input").val();
  if ($.trim(message) == '') {
    return false;
  }
  var convo_id = document.getElementById("convo_id").value;
  var msg = $('#msg').val();
  $.ajax({
    cache: false,
    type: "POST",
    url: 'send_chat.php',
    data: ({
      convo_id: convo_id,
      msg: msg
    }),
    success: function(data) {
    }
  });
};

$('.submit').click(function() {
  newMessage();
});

$(window).on('keydown', function(e) {
  if (e.which == 13) {
    newMessage();
    return false;
  }
});
Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27
Raiyu
  • 101
  • 10

1 Answers1

3

jQuery Ajax method return an XHR object. That object contains abort method. You can use that link as follows

var xhr=jQuery.ajax({
        });

Now you can use abort method. which will kill the request

xhr.abort();
Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27