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?

1
  • Wow, I've come a long ways...can't believe I was struggling with asynch. Haha! Commented Apr 2, 2013 at 21:24

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're very helpful! Thank you. Realizing my asynchronous error and using callbacks! stackoverflow.com/questions/2195161/…
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.

1 Comment

Duh! Thanks. Resolving this now.
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");
    });

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.