Question

I have a page with many checkboxes on it, I wrote a JS code that makes call to PHP page for each page, I want to refresh the page after the call has completed.. Here is my code

$(".matchFrnds").each(function(){  //For each CheckBox

        if($(this).is(':checked')){

            var sendData= $(this).val();

             $.post('Call to PHP Page',{sendData:sendData},function(data){


            window.location.reload();
                });
        }
        });

The problem is that the page reloads after completing few checboxes, so if there are 60 checkboxes, the page reloads after making call for 10 checkboxes. I also changed the place for window.location.reload(); but the results are same, I want that once the call for all the checkboxes is completed then it reloads.

Was it helpful?

Solution 2

It is really easy.
You just need to set a counter, and call reload() on the last one.
The idea would be to have another variable...

// Save the element to iterate in a variable
var matchFrnds = $(".matchFrnds"),
    //and save its length too
    length = matchFrnds.length;

//Iterate over it
matchFrnds.each(function() {
    // modify the counter
    --length;
    if ($(this).is(":checked")) {
        // do your things
        $.post( ... , function(data) {
            //do what you need to do with the data...
            // ....
            // ....
        });
    }
    //and, if it's the last element
    if (!length) {
        // LAST ITERATION!
        window.location.reload();
    }
});

And that's it.

OTHER TIPS

You can check how many calls you have finished then reload

var boxes = $(".matchFrnds:checked").length;
var calls = 0;
$(".matchFrnds").each(function(){  //For each CheckBox
        if($(this).is(':checked')){
            var sendData= $(this).val();    
            $.post('Call to PHP Page',{sendData:sendData},function(data){

               calls++; 
               if(calls >= boxes) {    
                 window.location.reload();
               }

            });
        }
  });

You could use the .ajaxStop-Event

http://api.jquery.com/ajaxStop/

you can try with this after complete your request:

location.reload();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top