Shira Ishikawa
Shira Ishikawa

Reputation: 140

Javascript not running in order

i have problem with my javascript not running in order on submit event. i have a form more or less like this:

<form id="myForm">
  <div>
    <button type="submit" name="submit">Submit</button>
  </div>
  <div>
    <div id="loading" style="display:none;"><img src="images/loading.gif"/></div>
    <div id="hasil" style="display:none;"></div>
  </div>
</form>

and a javascript function with ajax :

$('#myForm').submit(function() {
  $('#hasil').fadeOut('fast', function() {
    alert('a');
    $('#loading').fadeIn('fast');
  });
  $.ajax({
    type: 'POST',
    url: $(this).attr('action'),
    data: $(this).serialize(),
    success: function(data) {
      if(data=='0'){
        $('#hasil').html('Code Already Exist');
        $('#loading').fadeOut('fast', function() {
          alert('d');
          $('#hasil').fadeIn();
        });
      }
    }
  });
  return false;
});

it supposed to show #loading, hide #loading, then show #hasil. at first submit, it will run with no problem. but when i submit it at second time, the script not running at orderly from top to bottom, instead from point 'd', then 'a' (alert()).

i wonder why the script run like this? did i made a mistake somewhere?

Upvotes: 0

Views: 409

Answers (1)

user2970115
user2970115

Reputation: 483

Reference to jQuery API document: http://api.jquery.com/fadeout/

the callback is fired once the animation is complete.

So, if the ajax request was completed faster than the fade out animation, point 'd' will happen first and then point 'a'.

You can place the ajax request inside the fade out callback function to solve the problem.

$('#myForm').submit(function(e) {
    $('#hasil').fadeOut('fast', function() {
        alert('a');
        $('#loading').fadeIn('fast');
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data) {
                if(data=='0'){
                    $('#hasil').html('Code Already Exist');
                    $('#loading').fadeOut('fast', function() {
                        alert('d');
                        $('#hasil').fadeIn();
                    });
                }
            }
        });
    });
    return false;
});

Upvotes: 1

Related Questions