0

I'm trying to read product_info array returned from function getproductInfo containing a ajax call but I still getting undefined value on console.log. Also, I'm using a callback function but still doesn't work. Where am I wrong?

$(document).ready(function() {

    function successCallback(data)
    {
        var name = data.name;
        var image = data.image;
        var link = data.link;

        var product_info = [name, image, link];
        console.log(product_info); // Correct: show my product_info array
        return product_info;
    }

    function getProductInfo(prodId, successCallback) {
        $.ajax({
            type: "POST",
            url: "getProductInfo.php",
            data: "id=" + prodId,
            dataType: "json",
            success: function(data) {
                var p_info = successCallback(data);
                console.log(p_info); // Correct: show my product_info array
                return p_info;    
            },
            error: function()
            {
                alert("Error getProductInfo()...");
            }
        });

        return p_info; // Wrong: show "undefined" value
    }

    var p_info = getProductInfo(12, successCallback);
    console.log(p_info); // Wrong: show empty value
});
KaMZaTa
  • 535
  • 2
  • 9
  • 24

0 Answers0