2

I want to submit form using ajax and hide button and show message. I used "async:false" into ajax that's why button is not hiding. If I use "async:true" then it working.

$(document).ready(function (e) {

$("#submit_form").on('submit',(function(e) {

    $('#btn1').css('display','none');
    $("#show1").css('display','block');


 e.preventDefault(e);

var chkArray = [];
var chkArray1 = [];
$('#loading').show();
var inps = document.getElementsByName('chk_url[]');

//sleep(1000);

 for (var i = 0; i <inps.length; i++) {
  var inp=inps[i];
  if($(inp).is(':checked')){
   var site_url=$('#site_urls').val(inp.value);

   $.ajax({
    url: $('#site_urls').val(), 
    type: "POST",             
    data: new FormData(this), 
    contentType: false,       
    cache: false,             
    processData:false,
    async:false,        
    success: function(data)   
    {

     if(data=='done'){

            chkArray.push($('#site_urls').val());


     }else{

       chkArray1.push($('#site_urls').val()); 
     }
    }
   });
  }

 }



}));

});

Is there another way to execute hide code before ajax execution??

I have used "delay(1000)" and "sleep(1000)". I cannot use "setTimeout" function.

Jon
  • 121
  • 1
  • 10
  • Possible duplicate of [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – D B Sep 05 '17 at 11:51
  • use `async:true`, your `success` callbacks will be executed anyway when response arrive. Any strong reason for `async:false` ? Don't make user angry, waiting for the response. – yvoytovych Sep 05 '17 at 12:13

1 Answers1

0

Don't use the ajax call in for loop, use outside the loop,

I have change your code, let i know it is helpful..

  $(document).ready(function (e) {

$("#submit_form").on('submit',(function(e) {

    $('#btn1').css('display','none');
    $("#show1").css('display','block');


e.preventDefault(e);

var chkArray = [];
var chkArray1 = [];
$('#loading').show();
var inps = document.getElementsByName('chk_url[]');

//sleep(1000);
var fd = new FormData(); 

 for (var i = 0; i <inps.length; i++) {
  var inp=inps[i];
  if($(inp).is(':checked')){
    fd.append( 'site_urls', inp.value );
  }

 }


/*send call to server start here*/

   $.ajax({
    url: $('#site_urls').val(), 
    type: "POST",             
    data: fd, 
    contentType: false,       
    cache: false,             
    processData:false,
    async:false,        
    success: function(data)   
    {

     if(data=='done'){

            chkArray.push($('#site_urls').val());


     }else{

       chkArray1.push($('#site_urls').val()); 
     }
    }
   });

/*send call to server ens here*/

}));

});