I have a simple social networking site with chat functionality. I have used $.post
a lot in multiple pages.
The code works well on all pages except message.php
Ajax syncronous: Make the ajax call syncronous. This will stop its thread untill the response is back, easy to implement but comes with the downside that the user cannot type anymore untill request is solved
$.ajax({
url: 'bbs.php',
data: {a:a},
success: function(abc){
$(".showoff").html(abc);
},
async: false
});
Global variable check: make a global variable that checks the state of previous request and doesn't allow future ones until it is resolved:
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});
As you appear to want an autocomplete type setup, use a timer. Reset it on each keypress and after a delay send your post. In this example it will send 3 seconds after the last keypress.
$(document).ready(function(e) {
var timer;
$(".abc").keyup(function() {
var $input= $(this);
// Start timer
clearTimeout(timer);
// Start a new 3 second timer
timer = setTimeout(function() {
// Once the
var a = $input.val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
}, function(abc) {
$(".showoff").html(abc);
});
}, 3000);
});
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/Locpnk35/
This will avoid overloading your server as no more than 1 request every 3 seconds can come from the same user. If the response is slower than 3 seconds you may also need to disable the key handler while an Ajax request is in progress.
Simplest answer would be you allow your server to be spammed to the point that it stops responding (yet still recieving new connections). If the connections are not closed(resolved) in time you will also hit limitation of concurrent browser connections to domain (which I think is really happening - browser blocking you in making those request).
You either switch to sockets, or send text to server on set interval of time. Alternatively you dont allow next post, till previous is resolved.
Instead of allowing your server to be spammed, you can remove the handler before the first post and set it back again when the post returns.
$(document).ready(function(e) {
var $abc = $('.abc'); //good idea to cache those jQuery selectors!
function abcPost() {
$abc.off('keyup', abcPost)
var a = $(this).val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
},
function(abc) {
$(".showoff").html(abc);
$abc.on('keyup', abcPost)
});
}
$abc.on('keyup', abcPost);
});
This is good.
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});