Предотвратите многократные вызовы ajax при вводе нажмите

Я использую плагин чата php. Проблема с этим плагином чата заключается в том, что он прекрасно работает, когда сообщение отправляется с помощью нажатия кнопки, но когда он настроен на ввод, он вызывает слишком много вызовов ajax. Иногда он отправляет одно сообщение, а иногда отправляется 4 5 сообщений. Я перепробовал все решения, такие как определение переменной, чтобы проверить ее, но я не уверен, что мне здесь не хватает, это фрагмент функции, используемый для отправки сообщения

$("#text-messages-request").on("focus", "textarea.type-a-message-box", function() {
var ID = $(this).attr("id");
var URL = $.base_url + 'ajax/add_chat_ajax.php';

$('div.message-btn-target').html('<a href="#" id="' + ID + '" class="btn btn-default btn-sm send-message"><i class="glyphicon glyphicon-send"></i> ' + $.sendButton + '</a>');
//$('#type-a-message').remove();

user_is_typing(this, ID);

$(this).on('blur', function() {
stop_type_status();
});

// Input Handler
if ($.enterIsSend == true) {
var running = false;
$(document).bind("keypress", function(e) {
if (e.which == 13) {
if (running === false) {
running = true;
send_message(ID, URL);
}
return false;
}
});

$("a.send-message").on("click", function() {
if (running === false) {
running = true;
send_message(ID, URL);
$(".type-a-message-box").focus();
}
});
} else {
$("a.send-message").on("click", function() {
send_message(ID, URL);
$(".type-a-message-box").focus();
});
}
return false;
});

Пожалуйста, помогите, я застрял на этом в течение нескольких дней.
Существует функция чата в реальном времени, которая запускается, когда оба пользователя находятся в сети, и продолжает вызывать себя каждые 7 секунд.

setInterval("realtime_chat()", 7000);
function realtime_chat()
{
last_msg_id = $(".msg-div").last().attr("id");

var ID = $("#text-messages").attr("rel");

var R_URL = $.base_url + 'ajax/refresh_unreadMessages_ajax.php';
var URL = $.base_url + 'ajax/chat_realtime_ajax.php';
var I_URL = $.base_url + 'ajax/chat_last_id.php';

var dataString = 'id='+encodeURIComponent(ID);$.post(URL, dataString, function(html) {
var html_response = $(html);
var new_msg_id = html_response.attr("id");

if(new_msg_id !== last_msg_id)
{
$("#text-messages").append(html);

}

})// deal with update counter and typing status
$('ul#messages-stack-list li').each(function() {
cID = $(this).attr('id');
cString = 'id='+cID;
type_status(cID);
update_unMsg_counter(R_URL, cString, cID, 'realtime');
});

title_unread_counter();

return false; }

Просто добавить, что если в базе данных хранится какое-то новое сообщение.
и вот мой HTML текстового поля

<div id="type" class="collapse border-top">
<textarea type="text" class="form-control border-none" id="type-a-message-  box" placeholder="Write the message"></textarea>
</div>

функция для получения содержимого textarea находится сверху, а функция отправки сообщения выглядит следующим образом

function send_message(ID, URL)
{
var textarea = $('textarea.type-a-message-box').val();
if ($.trim(textarea).length == 0)
{
alert($.emptyBox);
} else {
$.ajax({
type: "POST",
url: URL,
data: {id: ID, message: textarea},
cache: false,
beforeSend: function() { $('#loadingDiv').show(); },
error: function() { $('#loadingDiv').hide(); $('#errorDiv').html('<p>'+$.ajaxError+'</p>'); },
success: function(html) {
$('#loadingDiv').hide();
$("p.no-messages").remove();
$("#text-messages-request").html(html);
$("#text-messages").attr("rel", ID);
stop_type_status();
$(".type-a-message-box").focus();

}
});
}
}

Надеюсь, что это поможет в формулировании решения

0

Решение

Скорее, чем нажатие клавиши использование KeyUp событие.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector