1

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.

$(document).ready(function() {

    var $calendar = $('#calendar');

    $calendar.weekCalendar({

        ...

        data : function(start, end, callback) {
            var datas = getEventData();
            alert(datas); // Undefined???
        }
    });

If I inspect the object before returning it, it is defined.

function getEventData() {
        var dataString = "minDate="+ minDate/1000  + "&maxDate=" + maxDate/1000;
        //alert(dataString);return false;
        $.ajax({
                type: "POST",
                url: "busker_ops.php",
                data: dataString,
                dataType: "json",
                success: function(data) {
                    if(data != null) {
                            var jsonArray = new Array();
                            var jsonObj = {};
                            for(var i = data.length - 1; i >= 0; --i) {

                                var o = data[i];
                                var set_id = o.set_id;
                                var start = o.startOrig;
                                var end = o.endOrig;
                                var title = o.title;
                                var deets = o.deets;
                                jsonObj = 
                                    {
                                        "id":parseInt(set_id),
                                        "start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
                                        "end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
                                        "title":title,
                                        "body":deets
                                    };
                                jsonArray[i] = jsonObj;
                            }
                            alert($.toJSON(jsonArray)); // Defined!
                            return ($.toJSON(jsonArray));
                    } else {
                    }
                }
        });
    }

Any idea what I'm missing here?

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72
Corey Gwin
  • 150
  • 2
  • 12

3 Answers3

2
function getEventData() {
  function local() {
    console.log(42);
    return 42;
  }

  local();
}

Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.

Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • You're very helpful! Thank you. Realizing my asynchronous error and using callbacks! http://stackoverflow.com/questions/2195161/how-to-return-an-array-from-jquery-ajax-success-function-properly – Corey Gwin Nov 20 '11 at 02:22
1

Your getEventData() function returns nothing.

You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.

Jason LeBrun
  • 13,037
  • 3
  • 46
  • 42
0

I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).

$(document).ready(function() {

    // Declare variables
    var $calendar = $('#calendar');
    datas = "";
    set = 0;

    // Retrieves event data
    var events  = {
        getEvents : function(callback) {
            var dataString = "minDate="+ minDate/1000  + "&maxDate=" + maxDate/1000;
            $.ajax({
                type: "POST",
                url: "busker_ops.php",
                data: dataString,
                dataType: "json",
                success: function(data) {
                    if(data != null) {
                            var jsonArray = new Array();
                            var jsonObj = {};
                            for(var i = data.length - 1; i >= 0; --i) {

                                var o = data[i];
                                var set_id = o.set_id;
                                var start = o.startOrig;
                                var end = o.endOrig;
                                var title = o.title;
                                var deets = o.deets;
                                jsonObj = 
                                    {
                                        "id":parseInt(set_id),
                                        "start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
                                        "end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
                                        "title":title,
                                        "body":deets
                                    };
                                jsonArray[i] = jsonObj;
                            }
                            //alert($.toJSON(jsonArray));
                            callback.call(this,jsonArray);
                    } else {
                    }
                }
        });
        }
    }

    $calendar.weekCalendar({
        data : function(start, end, callback) {
                if(set == 1) {
                    callback(datas);
                    //alert(datas.events);
                }
        }
    });

    // Go get the event data
    events.getEvents(function(evented) {
        displayMessage("Retrieving the Lineup.");
        datas = {
                options : {},
                events : evented
        };
        set = 1;
        $calendar.weekCalendar("refresh");
    });

});
Corey Gwin
  • 150
  • 2
  • 12