1252748
1252748

Reputation: 15379

why does returning the jquery AJAX promise in this function fail to give me the data?

This AJAX works on jsfiddle

var a = $.ajax({
    url: "/echo/json/",
    type: "post",
    data: {
        json: JSON.stringify({
            a: true
        })
    },
    dataType: "json"
});

a.done(function (data) {
   console.log(data);
});

Why won't it work when I make a the function and return the AJAX promise?

var a = function () {
    return $.ajax({
        url: "/echo/json/",
        type: "post",
        data: {
            json: JSON.stringify({
                a: true
            })
        },
        dataType: "json"
    });
}

a.done(function (data) {

    console.log(data);

});

Is this not the correct syntax? Well, apparently not, but how can I build the AJAX request into the function? FIDDLE

Upvotes: 1

Views: 828

Answers (1)

Barmar
Barmar

Reputation: 782683

Since a is a function, you have to call it:

a().done(function(data) {
    console.log(data);
});

Upvotes: 5

Related Questions