-1

I have a container method for an ajax request:

function postRating(formData) {
    $.ajax({
        type: "POST",
        url: '/api/ratings',
        data: formData
    })
        .done(function () {
            return true
        })
        .fail(function () {
            return false
        })
        .always(function (msg) {
            //console.log(msg);
        });
}

which is called like so:

$('.episode-rating.like').click(function () {
    var formData = $("#episode-rating").serializeArray();
    formData.push({name: 'up', value: 1}, {name: 'down', value: 0});
    console.log(postRating(formData))
});

However postRating() returns undefined. Not sure what I'm doing wrong. I want to do some html processing if the ajax request is successfull and show an error otherwise.

Nick
  • 2,862
  • 5
  • 34
  • 68

2 Answers2

4

It is async, as mentioned above, so use callback:

function postRating(formData, cb) {
    $.ajax({
        type: "POST",
        url: '/api/ratings',
        data: formData
    })
        .done(function () {
            cb(true);
        })
        .fail(function () {
            cb(false);
        })
        .always(function (msg) {
            //console.log(msg);
        });
}

And then:

postRating(formData, function(result){
    console.log(result);
})

Or you can use promises:

function postRating(formData, cb) {
    return $.ajax({
        type: "POST",
        url: '/api/ratings',
        data: formData
    });
}

and then:

postRating(formData)
   .done(function(){
        console.log(true);
    })
   .fail(function(){
        console.log(false);
    });
Roman Bekkiev
  • 3,010
  • 1
  • 24
  • 31
0

This is an async call. If you want you can make your ajax call sync and then you can return from the container, otherwise you would have to implement callbacks on the container, which are invoked upon success, error and complete.

// Async = false
function postRating(formData) {
    return $.ajax({
        type: "POST",
        url: '/api/ratings',
        data: formData,
        async: false
    });
}

// Callbacks
function postRating(formData, successCallback) {
    $.ajax({
        type: "POST",
        url: '/api/ratings',
        data: formData,
        success: function (data) {
            successCallback.apply(this, [data]);
        }
    });
}
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100