Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning callbacks for a $.post call in jQuery

Tags:

jquery

I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error"); 
        },
        success: function(data) {
            alert(data);    
        }
    });
});

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

like image 790
Mohamad Avatar asked Dec 05 '22 21:12

Mohamad


1 Answers

You're passing the callbacks as part of the data to be posted, so they're getting evaluated as part of the post call. Try this:

$.post(url, { comment: text }, function(data) {
        alert(data);    
});

or

$.ajax(url, { data: { comment: text },
    type: "POST",
    beforeSend: function() {
        alert("before send");
    },
    error: function() {
        alert("error"); 
    },
    success: function(data) {
        alert(data);    
    }
});
like image 120
Andrew Cooper Avatar answered Dec 22 '22 13:12

Andrew Cooper