Any way to stop the code execution and then resume it? For example, next code will not run until a flag value is changed and then resume it.
Edit: I have a code that starts a loop of AJAX requests and I need to control (with a flag if its possible) thats loop when the user visits other tabs of the browser to stop it. Then, when the user returns to the application, loop would resume.
The problem would be solved with setInterval to AJAX requests and a flag to stop them. But I think that is more correct to do the loop of AJAX requests from the success ajax function, i.e. when the response is done, because I am using a MVC pattern and have the ajax function in a model and the called is done from de view. And then, the loop with setIntervalwould start in a wrong side
however, I am thinking that "setInterval" could be in the AJAX called function
You can detect when the browser tab becomes inactive using any of many methods (I'm fond of using JQuery to set focus and blur events on the document, but there are other techniques), but I think the pattern you're looking for is the "closure that sets its own new timeout on completion" instead of setInterval.
var active = true;
function myloop()
{
if (active)
{
$.ajax(/*...*/).done(function(j)
{
/* do stuff */
window.setTimeout(myloop, interval);
});
}
}
In this scenario you'll need to set active = true and call myloop() again when you detect the tab or window becoming active again. When the tab becomes inactive, set active = false. The currently running AJAX request will complete safely; but further requests won't be made until you manually restart the loop.
Related
$('#gd').on('click', function(){
// move up and down DOM elements
// some ajax procedure to store new values on database (php/mysql)
});
Is there any danger to repeating this click very quickly for a long time?
For example - if the connection is poor - will the ajax will not complete each time?
I tested on my live server - seems there is no problem, but... I'm still concerned.
And what is the way to avoid possible problems it this scenario - i.e. if a user keeps clicking very quickly on the #gd button.
This "Danger" would be more accurately described as undesired behavior. However, it is indeed issue which should be treated - as sending multiple request when only 1 is required would consume resources on both client and server with no reason.
If you would like to prevent the user from clicking the button while the request is being processed, disable the button after the client send it it, and re-enable it after response processing complete:
$('#gd').on('click', function(){
// 1. do some stuff with DOM
// 2. disable button + make ajax call
$.ajax({someRequestOptions})
.always(function() {
// 3. re-enable button
});
});
Working on a platform, to enable auto-ticketing functionality. For which a REST API request is used for ticket creation. Unfortunately, there are 2 requests popping simultaneously, which results in creating duplicated tickets.
How to handle such case and send only one of these requests?
Tried adding the 2nd request in the response callback of the first, though this does not seem to work.
if (flag == 1){
logger.debug("Node-down alarm-Request raised - +sitn_id);
clearTimeout(mouseoverTimer);
mouseoverTimer = setTimeout(function(){
logger.debug("Inside Call back function - ");
//function call for ticket creation
incidentRequest(sitn_id,confUtil.config.mule_url);
}, 10);
You really should show more of the code that makes the request, though it seems as if you are doing some ajax inside your 'incidentRequest', so I will presume that (if that isn't what you are doing, then please, show your code....) - and since you tags say javascript and jquery - well, here goes...
To stop the 'double send' in an AJAX call, it is simple:
function incidentRequest(sitn_id,confUtil.config.mule_url){
// stop the double by clearing the cache
$.ajaxSetup({cache: false});
// continue on with the AJAX call
// presuming the url you want is confUtil.config.mule_url
// and the data you want to send is sitn_id
$.post(confUtil.config.mule_url, 'sitn_id=' + sitn_id, function (data) {
// do cool stuff
});
}
Hopefully that will help you get moving. If not, then we will need more code of what is going on around all this.
I have a use case like this:
When user clicks on a radio button I make an ajax call to get some information dependant on the user selection. When user clicks on a link I use the information form AJAX call to display an alert.
I need:
to ensure the result of the ajax calls are written in the correct
order
If the user to open the alert, before then the AJAX call is finished I want to display him a waiting icon, otherwise display him
the alert
If the response from AJAX doesn't comein 2s I will display the alert anyway
I am not really asking how to do this specific use case in JS, since I can figure out how to combine timer, jQuery ajax callbacks and so on.
I see the problem in a more generic way:
we have three events (AJAX success, user click, timeout) and I wanto to associate some code to be triggered by some conditions on the events. Is there any framework that allows to associate actions to a combination of events?
Or am I just using the wrong approach?
1 - If the response order is important, it's not useful to allow multiple parallel requests, which means when the user will select a radio button, you should queue the operations. That's very easy to achieve with promises.
E.g.
var promiseQueue;
function processRequest(radioValue) {
return $.ajax({ ... }).done(/*handle request*/);
}
function onRadioClicked() {
var radioValue = this.value; //assuming this is your radio element
//if the queue was initialized, queue our next operation using "then",
//otherwise process the request directly and initialize the queue with the
//returned promise.
promiseQueue = promiseQueue?
promiseQueue.then(processRequest.bind(null, radioValue)) :
processRequest(radioValue);
}
2 - Do not use alert as it will block your UI. You can use jQuery UI's Dialog plugin or anything similar. Everytime a response is processed, you can check promiseQueue.state() to see if there are other requests to be processed or they all have been processed.
3 - You can pass a timeout configuration to $.ajax to allow a maximum time for the request to complete. Have a look at https://api.jquery.com/jQuery.ajax/
OK, So I am creating a entire web app using AJAX with some local storage etc.
The issue I am having is sometimes I double click, or click tabs back and forth quickly which invoke a $.post call.
Problem lies when the callbacks are fired, they are called back and keep overwritting eachother until the last call has came back.
Obviously that is a problem. What I need to do is cancel current POST calls and just get the last callback.
I have tried:
// Make Call:
if(call != undefined){
call.abort();
}
var call = $.post(url,{do:'stuff'},function(response){
// callback stuff:
},'json');
Keeps saying its undefined regardless, I rather use .POST than .AJAX if possible.
Thanks for your help in advance!
Simply unbind the click event on click, re-bind it on callback.
One thing you can do if canceling doesn't catch all your pending XHRs: increment a counter and pass it to your backend to keep old responses from clobbering new ones. Just have your backend include the counter value in the response, and then your callback can compare it to the local counter before overwriting.
I have a php script that outputs json data. For the purposes of testing, i've put sleep(2) at the start.
I have a html page that requests that data when you click a button, and does $('.dataarea').append(data.html)
(php script returns a json encoded array. data.html has the html that i want to put at the end of <div class="dataarea">...HERE</div>.
The trouble is, if i click the button too fast (ie. more than once within two seconds (due to the sleep(2) in the php script)), it requests the php file again.
how can i make it only do one request at a time?
i've tried this (edited down to show the important parts):
amibusy=false;
$('#next').click('get_next');
function get_next() {
if (amibusy) {
alert('requesting already');
}
else {
amibusy=true;
// do the request, then do the append()
amibusy=false;
}
}
but this doesn't seem to work. i've even tried replacing the amibusy=true|false, with set_busy(), and set_not_busy(). (and made a function am_i_busy() { return amibusy; })
but none of this seems to work. what am i missing?
If you're in jQuery the amibusy would be jQuery.active which contains a count of currently active AJAX requests, like this:
if(jQuery.active > 0) { //or $.active
alert('Request in Progress');
}
Keep in mind that in jQuery 1.4.3 this becomes jQuery.ajax.active.
Disable the button in the click event and enable it again when the request is finished. Note that the request is asynchronous (i.e. "send request" returns immediately), so you must register a function that is called when the answer comes in.
In jQuery, see the load() function and the success method plus the various AJAX events which you can tap into with ajax().
I'm wondering about your "do request" logic. Whenever I've done calls like this they've always been asynchronous meaning I fire the request off and then when the response comes another function handles that. In this case it would finish going through that function after setting the callback handler and set your value of amibusy back to false again before the request actually comes back. You'd need to set that variable in the handler for your post callback.
Could you use the async variable?
http://api.jquery.com/jQuery.ajax/
asyncBoolean Default: true
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Cross-domain requests and dataType:
"jsonp" requests do not support
synchronous operation. Note that
synchronous requests may temporarily
lock the browser, disabling any
actions while the request is active.