ProNotion
ProNotion

Reputation: 3692

jQuery $.post success function never fires

I have a $.post which using Fiddler I can see always posts successfully but my success function is never fired.

A successful post to the url returns a 1 or failure returns a 0, on each occasion I have tested it returns the expected value of 1 so I'm at a lost as to what I'm doing wrong?

if ($('#mycheckbox').prop('checked')) {
    $.post('/base/MailingList/Subscribe/',
        {
            listId: $('#mycheckbox').val(),
            name: $('#subscriber-name').val(),
            email: $("#subscriber-email").val()
        },
        function(response) {
            console.log(response);
        });
}

Upvotes: 5

Views: 13380

Answers (3)

Ivan Sokolov
Ivan Sokolov

Reputation: 1

In my case the problem was header with wrong MIME type ("application/json" instead of "text") in php file on server. If you send header that doesn't match type of data cause an error and $.post calls fail function.

Upvotes: 0

Jay
Jay

Reputation: 238

I'm not sure if this will help or not, but I always use fully qualified urls when I do any asynchronous calls. You may want to try:

$.post('http://mydomain.com/base/MailingList/Suscribe/', ...

Additionally, you will likely want your handling function to recieve all three argument from the callback (data, textStatus, jqXHR). This way, you can look at the txtStatus to verify if you have success or not.

Upvotes: 0

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

Stick another function as a final callback. That function will run in the failure case.

The way jquery recommends doing it is this:

var jqxhr = $.post( "example.php", function() {
   alert( "success" );
})
.done(function() {
    alert( "second success" );
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
 });

Upvotes: 10

Related Questions