tags:

views:

460

answers:

2

Hi, I'm using the following piece of code to login a user via Ajax.

  //Capture the login_ajax form
  $("#login_ajax").submit(function () {
    //First we fade out the header-login div
    $("#header-login").fadeOut('fast', function() {
      $(this).html("Loading").fadeIn('fast'); //Fade in loaading
    });
    $.post("db/login.php",
           { username: $("#username").val(), password: $("#password").val() },
           function(data) {
             $("#header-login").fadeOut('fast', function() { //Fade out loading
               $(this).html(data).fadeIn('fast'); //Fade in data
             });
           });
    return false;
  });

My problem is, because my request is being processed so fast, the fade effects overlap eachother and I'm just stuck with "Loading", even though the request returns some data to be displayed. Am I doing this wrong?

I can't use jQuery's ajaxStart and ajaxStart because I use other ajax forms on my site and don't want them to trigger the "Loading"

Thanks for your time

+3  A: 

Try this:

  //Capture the login_ajax form
  $("#login_ajax").submit(function () {
    //First we fade out the header-login div
    $("#header-login").fadeOut('fast', function() {
      $(this).html("Loading").fadeIn('fast'); //Fade in loaading
    });
    $.post("db/login.php",
           { username: $("#username").val(), password: $("#password").val() },
           function(data) {
             $("#header-login").stop().fadeOut('fast', function() { //Fade out loading
               $(this).html(data).fadeIn('fast'); //Fade in data
             });
           });
    return false;
  });

When you call .stop(), callbacks are not fired, this will prevent the .html("Loading") from firing after. See here for a full read.

Nick Craver
Thank you so much, works like a charm.
soren.qvist
A: 

You can try posting the form in the callback of the first fadeIn method (line 5 of your code sample). If I'm not mistaken, that should guarantee a more elegant chaining of those animation effects.

çağdaş