views:

29

answers:

2

Function socialbookmarksTableData(data) is called by another function to generate the content of a table -- data is a JSON object. Inside the function i call 2 other functions that use getJSON and POST (with json as a return object) to get some data. The problem is: though the functions execute correctly i get undefined value for the 2 variables (bookmarkingSites, bookmarkCategories). Help with a solution please.

    function socialbookmarksGetBookmarkCategories(bookmarkID)
    {
        var toReturn = '';
        $.post("php/socialbookmark-get-bookmark-categories.php",{
            bookmarkID: bookmarkID
        },function(data){
            $.each(data,function(i,categID){
                toReturn += '<option value ="' + data[i].categID + '">' + data[i].categName + '</option>';
            })
            return toReturn;
        },"JSON");
    }

    function socialbookmarksGetBookmarkSites()
    {
        var bookmarkingSites = '';
        $.getJSON("php/socialbookmark-get-bookmarking-sites.php",function(bookmarks){

            for(var i = 0; i < bookmarks.length; i++){
                //alert( bookmarks[i].id);
                bookmarkingSites += '<option value = "' + bookmarks[i].id + '">' + bookmarks[i].title + '</option>';
            }
            return bookmarkingSites;
        });
    }
    function socialbookmarksTableData(data)
    {
        var toAppend = '';
        var bookmarkingSites = socialbookmarksGetBookmarkSites();


        $.each(data.results, function(i, id){

            var bookmarkCategories = socialbookmarksGetBookmarkCategories(data.results[i].bookmarkID);
    //rest of the code is not important
        });
    $("#searchTable tbody").append(toAppend);
}
A: 

You return the variables from the callback functions, not the functions that you actually call. After the callback functions are called control is returned to the functions which have no return statements, so they 'return' undefined by default. You need to return values from socialbookmarksGetBookmarkCategories and socialbookmarksGetBookmarkSites not just from callback functions within them.

Craig
now i get an empty string.
A: 

You need to execute the code in your socialbookmarksTableData function as a response to the $.getJSON call. The problem is that you are returning right away, but the JSON callback hasn't yet fired.

Raul Agrait