Reload the page after ajax success

bosniamaj picture bosniamaj · Oct 24, 2011 · Viewed 123.6k times · Source

I have some problems with redirecting/reloading after a successful ajax call. Here is the situation:

I have item for deletion saved in an array. When I click on a button it calls for PHP file via ajax, and after success I need to reload the page. But I have some problem doing this. I searched the internet and couldn't find a working solution.

I have PHP file which goes through the array deleting item by item from the database.

foreach($arrayVals as $key=>$val)
{
    //bla bla
}

Also, I have jQuery part:

$("#button").live("click",function(){
    $.ajax({
        url, data, type... not important
        success: function(html){
                    location.reload();
                }
    });
});

I mean, the code works, but not good. It does delete items, but not all of them and then it reloads the page. Like, if I have 10 items to delete, it deletes like 6-7, and 3-4 items stay undeleted.

It acts like it reloads the page too soon, like PHP file does not have enough time to process everything :D

Answer

Vikas Naranje picture Vikas Naranje · Oct 24, 2011

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});