I want to show alert message after some perticulate time as 'Do you want continue?' If user say yes then ajax call must be run in background otherwise cancel the ajax call. So please tell me how I can place time condition in ajax call response?
Asked
Active
Viewed 5,444 times
3
-
ajax calls usually run in the background – madalinivascu Jul 27 '16 at 05:50
-
Browsers don't support background tasks. – Hatim Aug 07 '18 at 16:44
5 Answers
0
In technical terms it called as Long Polling request.. its something like this
function longPolling()
{
$.ajax({
//..... your ajax configurations like url, type, dataType...etc
success: function(data){
// your code for handle success response
setTimeout(function(){
longPolling();
},5000) // call again after 5 seconds
},
error: function(xhr){
// your code for handle error response
setTimeout(function(){
longPolling();
},5000) // call again after 5 seconds
}
};
});
longPolling();// call where ever you need
I hope it help to you

Haresh Vidja
- 8,340
- 3
- 25
- 42
0
var time = 5000;
setTimeout(function() {
if (confirm('Do you want continue?')) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
});
} else {
// Do nothing!
}
}, time)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Iceman
- 6,035
- 2
- 23
- 34
-
It's not that easy to decipher what the original poster wants, but your code is working fine, _and_ possibly doing what is asked for. I would suggest replacing `5000` with `1000`, or maybe even `700`. (The asker didn't specify a time.) – Henke May 06 '21 at 16:03
-
since OP didn't specify, kept it open as a variable. line 1 can be changed to what fits your use case best. Anyways, this is so old- happy to see ppl looking at it 5 years after. Among my first posts, I think :) – Iceman May 17 '21 at 12:02
0
What i understood from your question is that the ajax call will be made before you ask the user "whether you would like to continue or not" correct?
And i believe you wanted to make sure the user want to wait if the ajax call is taking long time?
if this is the case you just set a flag on user press "no" and just abort the ajax call
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
});
//when user pressed no call the below function if the ajax is not completed
jqxhr.abort()

Sooraj T R
- 36
- 3
-1
window.setTimeout(function () {
if (confirm('Do you want continue?')) {
// Do some ajax?
} else {
// Do nothing!
}
}, 5000);

gotnull
- 26,454
- 22
- 137
- 203
-
-
1my friend, "ajax call must be run in background". your code will execute in UI thread.The right answer is, browsers don't support background tasks. – Hatim Aug 07 '18 at 16:43