0

is there a way in ajax to wait until ajax is done, before calling the function again? Only if a button was pressed during ajax request.

    $(document).ready(function(){
       $_button.on('click',function(){

       //if ajax is running, wait until done!
       init();
      });
    });

    function init(){
    //this function should be called again, when ajax is done
    }

    function ajax(){

    ..
    //ajax code
    ..

    }

Thanks a lot

2 Answers2

1

You can use the following:

$(document).ajaxStop(function(){
  // code which gets executed once ajax is done
});

By this way, once the ajax request gets completed, this will perform the requested action.

Hope this may help.

Nikhil Gyan
  • 682
  • 9
  • 16
  • I have many ajax requests.. not only this one. If a user clicks on the button again the variables initialitation should start again, but i have to wait for ajax success, if not they will be overridden ... – rasslstudio Nov 21 '19 at 08:12
  • 1
    in that case you can use the following to facilitate your requirement: $(document).ajaxStart(function() { $_button.attr("disabled", true); }); $(document).ajaxStop(function(){ $_button.removeAttr("disabled"); // code which gets executed once ajax is done }); – Nikhil Gyan Nov 21 '19 at 08:27
0

I solved the problem by overriding the global variables with variables inside the save function.

So on ajax success I can take the predefined variables inside the function instead of the variables outside the function.

function savePicture(){

      var  $_btn_edit = $btn_edit;
      var  $_btn_save = $btn_save;
      var  $_gui_resize = $gui_resize;
      var  $_img = $img;
      var  $_picture = $picture;

// here ajax request

success: function(data){
  //on ajax success
    $_picture.replaceWith($(data);
}

Thanks a lot!