In my rails app, using jquery slider. In stop event of slider, there is ajax request. If user continuously sliding slider there are too many pending ajax requests and my system get hang. I have used:
1:
function slide_stop(event, ui){
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$.xhrPool.length = 0
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
$.xhrPool.abortAll();
$('span#imgLoader').html('<img src="/assets/ajax-loader.gif">');
$.ajax({
type: 'get',
dataType: 'json',
url: 'some_url',
data: { is_ajax: true }
}).done(function(response){
$('span#imgLoader').empty();
});
}
Initialize slider,
$elt.slider({
min:0,
max:100,
value:50,
slide: slide_range,
stop: slide_stop
}).each(function(){
add_range_label($range_elt);
});
All ajax requests get stopped/in not modified state. But last request takes too long time to complete. No result again same hanging state.
2:
var request = $.ajax(
{
type: 'POST',
url: 'someurl',
success: function(result){}
});
then,
request.abort();
Not working. Too many requests are still in pending state.
I don't know what is wrong with it.
I tried using 'jquery-throttle-debounce'. Included file 'jquery.ba-throttle-debounce.min.js'
Applied jQuery.debounce to stop event for slider.
$("#slider").on( "slidestop", $.debounce( 240, slide_stop ) );
I tried by reducing time delay. But no expected result. Same case as above.
You can use a plugin such as http://archive.plugins.jquery.com/project/AjaxManager.
Also, as Javis mentioned you are best off to also incorporate a delay before sending the response so that you don't needlessly overload your server with requests. Instead of using time differences or arrays I would just keep a reference to the last ajax request created. You would abort that request each time a new one is made.
// just putting these here for example, you would want to associate them with each instance of your slider control.
var timeout, last_request;
function slide_stop(event, ui){
$('span#imgLoader').html('<img src="/assets/ajax-loader.gif">');
// clear the timeout so a previous request won't be sent
clearTimeout(timeout)
// set the request to be sent in .5 seconds
timeout = setTimeout(send_request, 500);
}
function send_request(){
// abort the last request if there is one
if(last_request){
last_request.abort();
}
last_request = $.ajax({
type: 'get',
dataType: 'json',
url: 'some_url',
data: { is_ajax: true }
}).done(function(response){
$('span#imgLoader').empty();
// set the last request to null so that you dont abort a completed request
//(this might not be necessary)
last_request = null;
});
}
Try to throttle those requests, so many request to server can cause a performance issue on your server side, because remember that each ajax call is an apache (or whatever your webserver is) request, which costs memory and cpu. And remember that excesive requests can cause a DDoS.
Remember that as an user, i can start playing with the slider so much as i like, causing a ton of requests.
You should add something like:
var requests = [];
var lastCall = (+new Date()); // parenthesis just in case of minify
var timeDiff = 1000;
function sliderStopCallback() { // this will be called each time the slider stop sliding
if(timeDiff < 400) {
return;
}
abortAll();
requests.push( $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){}
}) );
}
function sliderStartCallback() { // this will be call each time the user start to slide
timeDiff = (+new Date()) - lastCall;
lastCall = (+new Date());
}
function abortAll() {
var l = requests.length;
while(l--) {
requests[l].abort && requests[l].abort(); // the if is for the first case mostly, where array is still empty, so no abort method exists.
}
}
That way, each request will be sent at least on 400 milliseconds, preventing calls every 2 seconds.
This should work, but please notice that i havent tested it, so if you're going to try it please remember that it is a general idea, not a precise solution.
Good luck.
As said in comments, it's best to not send the request until the slideStop event. This way requests are not sent every time the value is changed, and thus server load is much less of an issue.
function ajaxrequest(){
$.ajax(....);
}
$("#slider").on("slideStop", function() {
ajaxrequest();
});
Related
For example, a user want to login, the connection is slow or the request is stuck into some network , then the user waits, but sometimes is better resend the request than waiting.
Questions:
What would be the desirable waiting time? (no uploading files, just
simple login) I've put 15 secs, but maybe it's too much.
What's the best solution?
1) Keep the user waiting till he decides to click login again
2) Set an ajax timeout
$.ajax({
url: '{{ url('/login') }}',
data: data,
method: 'POST',
timeout: 15000,
and display them an error
error: function(data, status, error){
if(status==="timeout") {
var errorString = 'Please retry. Ref Timeout';
}
3) do an auto retry (code)
$.ajax({
url : 'someurl',
type : 'POST',
data : ....,
tryCount : 0,
retryLimit : 3,
...
error: function(data, status, error){
if (status == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
4) Use a wrapper function over the ajax
setTimeout(function(){
$.ajax({...})
}, 15000);
5) Some other options
I would personally do a mix, that means, try 2 times and the fall, you can use this code:
$.ajax({
url: '{{ url('/login') }}',
data: data,
method: 'POST',
timeout: 10000, // sets timeout to 5000 = 5 seconds
retryCount: 0, // start retry count
retryLimit: 1, //will let you retry a determined number of times
error: function(data, status, error){
if(status==="timeout") {
this.retryCount++;
if (this.retryCount <= this.retryLimit) { //&& Date.now() - this.created < this.retryTimeout
console.log("Retrying");
$.ajax(this);
return;
}
else{
var errorString = 'Timeout';
}
Default server timeout is 30s, so it's proper timeout in Ajax.
Don't bombard server with re-logins (if it's too busy, you make it even worse).
Do not allow user to click login button once more while request is pending.
IMO there should be ajax without timeout and on error you should tell user to try again later.
$.ajax({
error: function (response) {
console.error(response); // Show error response to dev
alert('Something went wrong. Please try again later or contact administrator admin#email.com'); // Use pretty modal instead
}
})
You could you a library like https://github.com/inmar/patience_js that lets you define retry strategies and keep your code a lot cleaner.
Or better yet take a look at RxJS
where you can use an approach like the one suggested here: RxJS retry operator with ajax call
const doLogin = () => {
console.log('calling');
return $.ajax('...')
};
const stream = Rx.Observable.fromPromise(doLogin).retry(3);
stream.subscribe(log);
For example, say a page returns search results based on debounced user text.
How do you account for the case where an endpoint has a highly variable latency in which the second call can return before the first call.
E.g.
User is typing "books and movies" with a keyup debounce of 500ms
The user slightly pauses in the middle so the string is "books", this triggers a search call.
The user continues typing and finishes, triggering the second call with "books and movies".
The second call returns first, populating the list based on "books and movies".
Then the first call, which was delayed comes back and re-renders the list based on "books".
The user sees only "books" and is confused.
The surefire way to solve this is with a button to manually trigger the call. I'd like to avoid this though so I've increased the debounce but I'm wondering if there's a better way.
We suppose that you use jQuery to make ajax calls.
One solution is to use a pooling system: basically an array containing ajax requests.
Each time, a new request is emitted, you abort all request in the pool.
So you ensure that the last request made will be the only one that will end.
Here is the implementation of the pool:
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
jQuery(this).each(function (idx, jqXHR) {
jqXHR.abort();
});
jQuery.xhrPool.length = 0;
};
Here is an example on how to use it with the "search repository API" from GitHub (https://developer.github.com/v3/search/#search-repositories):
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
jQuery(this).each(function (idx, jqXHR) {
jqXHR.abort();
});
jQuery.xhrPool.length = 0;
};
$(document).ready(function(){
$("#SearchField").autocomplete({
source: function( request, response ) {
// First we abort all other request
jQuery.xhrPool.abortAll();
$.ajax({
url: "https://api.github.com/search/repositories",
method: "get",
dataType: "jsonp",
data: {
q: request.term
},
beforeSend: function (jqXHR) {
// Before sending the request we add it to the pool.
jQuery.xhrPool.push(jqXHR);
},
success: function(data) {
var items = new Array();
for(var i=0;i<data.data.items.length;i++)
{
items.push(data.data.items[i].name);
}
response(items);
}
});
},
minLength: 3,
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" >
<input type="text" id="SearchField" />
Javascript works synchronously so there is no possibility of race conditions if you write your code correctly.
I guess you are using ajax (ajax is supposed to be async, don't use sync ever, once you go sync, you can't go back) to get the query result. You are probably using some code like this:
var req=new XMLHttpRequest();
req.onreadystatechange=function(){
if (req.readyState==4){
if (req.status==200){
// Your callback here which shows autocomplete suggestions maybe?
}
}
}
Hold on to that req variable. So once you do a new request, you can simply discard the old request like:
req.onreadystatechange=null;
You can also abort the ajax request like:
req.abort();
The thing:
I have a page, which has to display undetermined number of images, loaded through AJAX (using base64 encoding on the server-side) one by one.
var position = 'front';
while(GLOB_PROCEED_FETCH)
{
getImageRequest(position);
}
function getImageRequest(position)
{
GLOB_IMG_CURR++;
$.ajax({
url: urlAJAX + 'scan=' + position,
method: 'GET',
async: false,
success: function(data) {
if ((data.status == 'empty') || (GLOB_IMG_CURR > GLOB_IMG_MAX))
{
GLOB_PROCEED_FETCH = false;
return true;
}
else if (data.status == 'success')
{
renderImageData(data);
}
}
});
}
The problem is that images (constructed with the renderImageData() function) are appended (all together) to the certain DIV only when all images are fetched. I mean, there is no any DOM manipulation possible until the loop is over.
I need to load and display images one by one because of possible huge number of images, so I can't stack them until they all will be fetched.
Your best bet would be to restructure your code to use async ajax calls and launch the next call when the first one completes and so on. This will allow the page to redisplay between image fetches.
This will also give the browser a chance to breathe and take care of its other housekeeping and not think that maybe it's locked up or hung.
And, use async: 'false' is a bad idea. I see no reason why properly structured code couldn't use asynchronous ajax calls here and not hang the browser while you're fetching this data.
You could do it with asynchronous ajax like this:
function getAllImages(position, maxImages) {
var imgCount = 0;
function getNextImage() {
$.ajax({
url: urlAJAX + 'scan=' + position,
method: 'GET',
async: true,
success: function(data) {
if (data.status == "success" && imgCount <= maxImages) {
++imgCount;
renderImageData(data);
getNextImage();
}
}
});
}
getNextImage();
}
// no while loop is needed
// just call getAllImages() and pass it the
// position and the maxImages you want to retrieve
getAllImages('front', 20);
Also, while this may look like recursion, it isn't really recursion because of the async nature of the ajax call. getNextImage() has actually completed before the next one is called so it isn't technically recursion.
Wrong and wrong. Don't user timers, don't chain them. Look at jQuery Deferred / when, it has everything you need.
var imgara = [];
for (image in imglist) {
imgara[] = ajax call
}
$.when.apply($, imgara).done(function() {
// do something
}).fail(function() {
// do something else
});
Try using setInterval() function instead of while().
var fetch = setInterval(loadImage, 2000);
function loadImage(){
position= new position; //Change variable position here.
getImageRequest(position);
if(!GLOB_PROCEED_FETCH){
clearInterval(fetch);
}
}
Following up on my question from the other day, I've run into another thing that now I've spent too many hours banging my head against.
Mostly, I'm having trouble getting the SUCCESS form to submit. I tried this as well:
jQuery form submit
Here's the code in a semi-functional fiddle:
http://jsfiddle.net/ZcgqV/
Essentially what happens is this:
I bind a method to the form's submission via onSubmit (rather than click)
On submit, it calls a remote server via jQuery .ajax() call
If the response is "PENDING", retry every 1s, nine times
On failure, don't submit the form
On success, submit the form
No matter what I try, I can't get the form to either submit when I want it to without going into a loop, or not submit immediately while it tries the remote server.
~Frustrated-trying-100-things-that-fail-ly yours...
Here's the code directly in case you dislike fiddles:
var retries = 0;
var success = false;
var token = "toki wartooth is not a bumblebee";
$(document).ready(function() {
// Attach the action to the form
$('#tehForm').attr('onSubmit', 'onsubmit_action(event)');
});
function async(fn) {
setTimeout(fn, 1000);
}
function pollServer() {
$.ajax({
type: "POST",
cache: "false",
url: "/remoteCall",
dataType: "json",
data: {
ref_token: token
}
}).done(function(data, code, jqXHR) {
switch (data.status) {
case "SUCCESS":
alert("Success");
success = true;
// --> HERE IS WHERE I WANT THE FORM TO SUBMIT <--
break;
case "PENDING":
if (retries < 9) {
retries += 1;
async(function() {
pollServer();
});
} else {
alert("Failed after 9 tries");
}
break;
case "ERROR":
alert("Error");
break;
default:
alert("Some kind of horrible error occurred");
break;
}
}).fail(function(jqXHR, textStatus) {
var statusCode = jqXHR.status;
alert("Request failed: " + statusCode + " " + textStatus);
});
}
function onsubmit_action(event) {
pollServer();
if (success === false) {
// RETURN FALSE DIDN'T WORK, SO I FOUND THIS
event.preventDefault();
}
}
EDIT:
Again, the real problem here is that I stop submission of the form. On SUCCESS, I want the form to submit. Currently if I use .submit() in SUCCESS, the AJAX is called again, starting the process over. What I want is the ACTION of the FORM to fire on SUCCESS only.
Trying to use as much of the original code as possible; here is a solution:
Post form with post back
http://jsfiddle.net/tpm7v/4/
Post form via Ajax
http://jsfiddle.net/tpm7v/5/
var retries = 0,
token = "toki wartooth is not a bumblebee",
sendRequest,
handelResponse,
postFormToServer,
$theForm = $('#tehForm');
$(document).ready(function() {
// Attach the action to the form
$theForm.bind('submit', onsubmit_action);
});
sendRequest = function() {
$.ajax({
type: "POST",
cache: "false",
url: "/remoteCall",
dataType: "json",
data: {
ref_token: token
},
success: handelResponse
});
};
postFormToServer = function() {
$.ajax({
type: "POST",
cache: "false",
url: "/remoteCallToTakFormData",
dataType: "json",
data: $form.serialize(),
success: function() {
alert('success!');
}
});
};
handelResponse = function(data, code, jqXHR) {
switch (data.status) {
case "SUCCESS":
postFormToServer();
break;
case "PENDING":
if (retries < 9) {
retries += 1;
setTimeout(sendRequest , 1000);
} else {
alert("Failed after 9 tries");
}
break;
case "ERROR":
alert("Error");
break;
default:
alert("Some kind of horrible error occurred");
break;
}
};
function onsubmit_action(evt) {
evt.preventDefault();
sendRequest();
}
Keep in mind I am going off the code your provided. You should be able to port this to work with your actual implementation. You may also want to try something like https://github.com/webadvanced/takeCommand to help clean up all the Ajax calls.
Please see my comment above for more information, but I think the problem you're seeing here is this:
Every time pollServer() fires, it's not only doing another ajax call, but it's prepping to do 9 possible ajax calls every second based on the retries loop. Since you're then setting another pollServer() call with the async() method, you're basically compounding your ajax calls out of control. You want to get the ajax call out of your retry loop, then you should at least be only getting 1 request a second, not 1, then 2, then 3, etc. I may have read the code wrong, but this is my best guess on what you're seeing.
UPDATE: I'm not sure my explanation was clear, so I thought I'd add some additional info. Basically, every time pollServer() is called and gets a PENDING response, it calls async, which registers a setTimeout(). setTimeout() keeps running every second, doing pollServer(), which then calls asynch, which registers another setTimeout() which also runs every second. Now you have two functions, which each then call setTimeout(), assuming they're still getting PENDING as a response from the server. So after 2 rounds of failed calls, you have 4 setTimeout() calls each firing an ajax call (and a new setTimeout) every second.
First off it should be: $('#tehForm').submit(onsubmit_action); or $('#tehForm').on("submit",onsubmit_action); or something like that. Never use the string form to pass a function. It uses the evil eval statement.
Next, after POST the data is already submitted. That is the whole reason for post. Why do you need all sorts of error handling in the done section. Fail should handle error handling.
If you are asking about how to try again after a timeout, try this:
Is it possible to check timeout on jQuery.post()?
I believe timeout will fall into fail.
So try this:
var retries = 0,
max_tries = 9,
success = false,
token = "toki wartooth is not a bumblebee";
$(document).ready(function() {
// Attach the action to the form
$('#tehForm').on("submit",submit_the_form);
});
function submit_the_form(e){
var dfd = $.ajax({
url : "sendTokenPolling",
data : {"token":token},
timeout : 5000 //you may want 1000, but I really think that is too short
});
dfd.done(function(){
//success, form posted
});
dfd.fail(function(){
//did not work/timedout
if (retries < max_tries){
retries += 1;
submit_the_form(e);
}
});
}
I would like to be able to have an ajax get update the text in a span tag each time it is fired.
$.ajax({
type: 'GET',
url: "JSON URL",
cache: false,
contentType: 'application/json',
dataType: 'json',
success: function(html){
$('#status_frame_span').prepend(html.status)
alert(html.status)
},
error: function(jq,stats,errmes) {
alert("Error" + errmes);
}
});
the first time it fires, the content of the json returned from the URL is properly prepended to the span. however for subsequent firings it is not updated.
How do I ensure that with each firing the content gets updated?
What triggers the call to the server? Is it a button or link inside of the HTML being updated? if it is, the event handler may be lost when the UI is updated. Or, something else is losing the event handler, which doesn't call the method to fire the get request, etc.
HTH.
Of course your view is updated only once: you are calling the server only once!
If, as your tags suggest, you are using long polling (please make sure that's the case, I'm not sure you have a very clear idea of what is an event, a poll and a distant call), then you need to make a new request each time you've received one!
In both your success and error handlers, you have to recursively make an AJAX call to the server. You also have to set a timeout for the calls, which could cancel them and start a new one after, for example, 30 seconds.
You should also implement some kind of throttling for recursive calls, unless you're 99.99% sure the server page will never send errors. Otherwise, you'll kill your client.
For the sake of completeness, I have to add this would be a great use-case for HTML5 SSE or WebSocket. But they're not ready for production usage yet.
it does not work that way - if the success callback is called - the connection has been closed so your long polling will be dead once the request is completed.
The idea behind long polling is that you keep the connection alive. Configure your server properly so that it will hold the connection open as long as possible (set timeout as high as possible).
Here's an approach from my coffee break (not tested):
Server
Every message has to end with the delimiter ::PART::
The server must be properly configured this means set the timeout as high as possible!
Client (Browser)
// setup longpoll, check all 250ms for new data in the stream
var myPoller = new LongPoll('some-url', 250);
// bind connection lost
myPoller.bind('longpoll:end', function(evt) {
alert('connection lost - trying reconnect');
});
// bind error event
myPoller.bind('longpoll:error', function(evt, errmsg) {
alert('error: ' + errmsg);
});
// bind data event
myPoller.bind('longpoll:data', function(evt, data) {
try {
// try to parse json
data = $.parseJSON(data);
// prepend
$('#status_frame_span').prepend(data.status);
} catch(e) {
// invalid json
alert('invalid json: ' + data);
}
});
longpoll.js
var LongPoll = function(url, timeout) {
// url we connect to
this.url = url;
// running?
this.isRunning = false;
// timer for checking the stream
this.timer = null;
// the length of the received data
this.dataLength = 0;
/*
The messages has to be delimited by the delimiter like:
first data::PART::second data::PART::third data::PART::
*/
this.delimiter = RegExp.new("::PART::", 'gm');
// residue from previous transmission
this.residue = ''
};
// connect to server
LongPoll.prototype.connect = function() {
var self = this;
// reset data length
this.dataLength = 0;
// reset residue
this.residue = '';
// start ajax request
this.xhr = $.ajax({
type: 'GET',
url: this.url,
cache: false,
contentType: 'application/json',
dataType: 'text',
success: function(){
// the connection is dead!
self.xhr = null;
// trigger event
$(self).trigger('longpoll:end');
// reconnect if still running
if(self.isRunning) {
self.connect();
}
},
error: function(jq,stats,errmes) {
// stop timer and connection
self.stop();
$(self).trigger('longpoll:error', errmes);
}
});
};
// process data
LongPoll.prototype.process = function(buffer) {
var self = this;
// check if there is anything new
if(buffer.length > this.dataLength) {
var newData = this.residue + buffer.substring(this.dataLength, buffer.length);
// reset residue
this.residue = '';
// store the new position
this.dataLength = buffer.length;
// split data
var dataParts = newData.split(this.delimiter);
// how many full parts?
var fullParts = newData.match(this.delimiter).length;
if(dataParts.length > fullParts) {
// pop residue (incomplete message)
this.residue += dataParts.pop();
}
$.each(dataParts, function(index, part) {
// broadcast data parts
$(self).trigger('longpoll:data', $.trim(data));
});
}
};
// check for data
LongPoll.prototype.receive = function() {
var self = this;
// connection still there?
if(this.xhr) {
// process buffer
this.process(this.xhr.responseText);
}
};
// start long poll
LongPoll.prototype.start = function() {
var self = this;
// set flag
this.isRunning = true;
this.timer = setInterval(function() { self.receive(); }, this.timeout);
this.connect();
};
// stop long poll
LongPoll.prototype.stop = function() {
// set flag
this.isRunning = false;
// clear timer
clearInterval(this.timer);
if(this.xhr) {
// abort request
this.xhr.abort();
}
};