iDentity iDentity - 4 months ago 9
Ajax Question

Why is my AJAX running 4 times

http://i.imgur.com/eFjV8Uv.png

$("#login").on('click', function () {
$(".login .col2, .login .signin, .login .close").fadeOut(500, function () {
$(".login .spinner").fadeIn(500);
var username = $("#username").val();
var password = $("#pw").val();
var data = "username="+username+"&password="+password;
$.ajax({
url: './api/prijava',
method: 'POST',
data: data,
dataType: 'json',
success: function(data) {
if(data.odg == 1) {
$(".login .spinner").fadeOut(500, function() {
$(".login .msg").append('Prijava uspješna').fadeIn(500, function() {
window.location = "./";
});
});
} else if(data.odg == 2) {
$(".login .msg").css('background-color', 'rgba(0, 255, 0, 0.5)').append('<span>Prijava uspješna! Dobrodošli...</span>').fadeIn(500, function() {
window.location = "./?first=true";
});
}
},
error: function(err) {
console.log(err);
}
});
});
});


Screenshot shows successful login (local language) but it should show it once, rather than 4 times. How can I make it load once and that's it?

Answer

The callback to fadeOut will run once per selected element. Instead you could use the promise to since when it resolves it only runs once:

$(selector).fadeOut(500).promise().then(function () {
    // do ajax call here
});
Comments