Search code examples
jqueryajaxtimeoutdelayloading

Need a timeout or delay on loading, Ajax jquery


Im making a loginscript and want to add a "feature" that after they submit the form, I want it to wait 1-2 seconds til it logins.

I have tried to get it to work, but the loading is just flashing by and do not delay as I want. See the following jquery:

$(document).on({
ajaxStart: function() { $body.addClass("loading");    },
 ajaxStop: function() { $body.removeClass("loading"); }    
});



$(document).ready(function() {

        $('#login').click(function()
            {
              var my_delay = 2000;
              var username=$("#username").val();
              var password=$("#password").val();
              var dataString = 'username='+username+'&password='+password;
              if($.trim(username).length>0 && $.trim(password).length>0)
              {
                 $.ajax({
                 type: "POST",
                 url: "ajaxLogin.php",
                 data: dataString,
                 cache: false,
                 beforeSend: function(){      
                   $("#login").val('Connecting...');},
                 success: function(data){
                   if(data)
                   {
                       $("body").addClass("loading").delay(6000);   // <-- This I want to show 2 seconds before or meanwhile it loads home.php
                       $("body").load("home.php").hide().fadeIn(1500);
                   }
                   else
                   {
                       $('#box').shake();
                       $("#login").val('Login')
                       $("#error").html("<span style='color:#cc0000'>Fel:</span> Felaktigt anv eller lös. ");
                   }
                 }
           });

        }
        return false;
    });

I tried this, but it just make loading stay and does not redirect to home.php after 3000ms.

 $("body").setTimeout("load('home.php');", 300);

Solution

  • $('body').delay(2000).queue(function( nxt ) {
        $(this).load('home.php');
        nxt();
    });