Reputation: 4508
I have Jquery+Ajax page that connects to server gets some data, and displays it. This is done all the time, function calls itself after it completes all task and starts to perform again and again. But If komputer loses internet connection everything stops. And when connections comes back again, nothing happens. Here is javascript code. How can I iprove it so it will continue to work after connection is back again.
$(document).ready(function() {
var a=1;
var max='23';
function kiosk()
{
if(a<max)
{
$.post('engine.php', { index: a },
function(result)
{
result = jQuery.parseJSON(result);
$('#main').css({'display':'none'});
$('#div_city').html(result.dest);
$('#div_price').html(result.price);
$('#div_price_pre').html('From ');
$('#div_price_after').html(' Euro');
$('#main').fadeIn(2000).delay(3000).fadeOut(2000, function()
{
$('#main').hide;
a++;
kiosk();
});
});
}
else
{
a=1;
kiosk();
}
}
kiosk();
});
Upvotes: 0
Views: 872
Reputation: 8532
I would suggest rather than using $.post you use
$.ajax({ type: "post" , success : function1() , failure: function2() }.
In function2() you can call koisk again after a timeout. and the succces would be the function you have created right now.
This link will help you understand the ajax function jQuery Ajax error handling, show custom exception messages
Eg Code snippet:
function kiosk()
{
if(a<max)
{
$.ajax({type : "POST" , url : 'engine.php',data: { index: a },
success : function(result)
{
result = jQuery.parseJSON(result);
$('#main').css({'display':'none'});
$('#div_city').html(result.dest);
$('#div_price').html(result.price);
$('#div_price_pre').html('From ');
$('#div_price_after').html(' Euro');
$('#main').fadeIn(2000).delay(3000).fadeOut(2000, function()
{
$('#main').hide;
a++;
kiosk();
});
},error : function (xhr, ajaxOptions, thrownError){ setTimeout(200,kiosk()) }
});
}
else
{
a=1;
kiosk();
}
} kiosk(); });`
Upvotes: 3
Reputation: 9822
Using jQuery.post
you are passing a callback which is executed only on success.
You should use jQuery.ajax
which has different callbacks. See documentation with complete
, success
and error
callbacks.
You could even use statusCode
to map a specific HTTP code to a custom function.
Upvotes: 0
Reputation: 3524
Script brokes because i think it throws exception. You can add your code try and catch block, and even if has errors you can continue to try.
try {
result = jQuery.parseJSON(result);
// do your work
} catch {
// call function again
}
Or you can use, jquery ajax, it has a onerror event.
Upvotes: -1