-2

I have a basic jQuery function:

$(document).on('click', '#myElement', function(){
    alert( getItemDescription('2') );
});

My function gets called, and runs the following as expected:

function getItemDescription(id){
        $.post("item_description.php", {id:id}, 
function () {
            // ...
        })
            .done(function (data) {
                    return data;
            })
            .fail(function () {
                return 'error';
            });
    }

When I look at the network tab in the console window, the .post() is successfully retrieving the correct info from item_description.php -- However my original function -- The alert simply replies undefined -- I have looked at the return manual in JS and read numerous posts on S.O. -- return is supposed to be able to return a literal is it not? What am I not seeing with this simple script? How do I get the retrieved variable data from getItemDescription into the alert ?

Zak
  • 6,976
  • 2
  • 26
  • 48

2 Answers2

0

Your second function doesn't return anything at the moment, what you need is

function getItemDescription(id){
        return $.post("item_description.php", {id:id}, 
function () {
            // ...
        })
            .done(function (data) {
                    return data;
            })
            .fail(function () {
                return 'error';
            });
    }
bugs
  • 14,631
  • 5
  • 48
  • 52
0

What you should do is call inside .done. One example is:

function getItemDescription(id,f){
        $.post("item_description.php", {id:id}, 
function (data) {
            // ...
        })
            .done(function (data) {
                    f(data);
            })
            .fail(function () {
                return 'error';
            });
    }

$(document).on('click', '#myElement', function(){
    getItemDescription('2',alert);
});

also you should not use .done in this case, since data is already retrieved in previous chained call. if you want to catch all, use .finally

dcluo
  • 66
  • 3