Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: ajax runs both handlers - done and fail

Tags:

jquery

I have an ajax call like

    $.ajax({
        type: 'POST',
        url: 'addVideo',
        data: {
            video_title: title,
            playlist_name: playlist,
            url: id
            // csrfmiddlewaretoken: '{{ csrf_token }}',
        },
        done: bootstrap_alert.success('video saved successfully'),
        fail: bootstrap_alert.error('There were some errors while saving the video. Please try in a while')
    });

and actions as

// setting up alerts on action
bootstrap_alert = function() {}
bootstrap_alert.success = function(message) {
  $('#feature').prepend('<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>');
}
bootstrap_alert.error = function(message) {
  $('#feature').prepend('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>');
}

When the front end makes ajax call, I see both the notifications at the same time

video saved successfully
There were some errors while saving the video. Please try in a while

Is that I am not making the ajax call correctly?

UPDATE
changing done to success results in same behavior

// send the data to the server using .ajax() or .post()
        $.ajax({
            type: 'POST',
            url: 'addVideo',
            data: {
                video_title: title,
                playlist_name: playlist,
                url: id
                // csrfmiddlewaretoken: '{{ csrf_token }}',
            },
            success: bootstrap_alert.success('video saved successfully'),
            fail: bootstrap_alert.error('There were some errors while saving the video. Please try in a while')
        });

The server response is HTTP/1.0" 200 3200, I believe the fail shouldn't get called

like image 928
daydreamer Avatar asked Aug 06 '12 22:08

daydreamer


1 Answers

The values are expected to be functions, callbacks. But, what you are doing is calling them right away. Wrap your callbacks around in anonymous functions.

$.ajax({
  type: 'POST',
  url: 'addVideo',
  data: { video_title: title, playlist_name: playlist, url: id }
}).done(function(){
  bootstrap_alert.success('video saved successfully');
}).fail(function(){
  bootstrap_alert.error('There were some errors while saving the video. Please try in a while');
});
like image 156
Alexander Avatar answered Oct 29 '22 04:10

Alexander