Question

I am trying to have a function grab an object from a php file on another page. I'm using the jQuery ajax function to to do the json grab, which is working correctly. The issue is when I try to return that object from the function.

The first time I log the object (from within the success function) it is correct in the console, but the returned object from the function getGantt() logs as "undefined".

How do I get this object out of the function?

My code:

    function getGantt(requestNumber){
        var ganttObject;
        $.ajax({
               type: "POST",
               url: "get_gantt.php",
               data: {request_number: requestNumber},
               success: function(returnValue){
                     ganttObject = $.parseJSON(returnValue);
                    console.log(ganttObject); //this logs a correct object in the console

                }
        });
        return ganttObject;
    }

    $(function(){ //document ready function

        var requestNumber = $('#request_number').text();

        var ganttObject = getGantt(requestNumber);
        console.log(ganttObject); //this logs "undefined"

    }); //end document ready function
Was it helpful?

Solution

The A in Ajax is an important part of the acronym. Asynchronous JavaScript and XML is asynchronous.

$.ajax({success:someFunction}) means Make an HTTP request and when the response arrives, run someFunction

return ganttObject runs before the response arrives.

You should do anything you want to do with the data inside someFunction and not try to return data to the calling function.

OTHER TIPS

The A in AJAX stands for asynchronous. So the call immediately returns and as soon as it finishes, the success callback is called.

So, simply change your code to use a callback:

function getGantt(requestNumber, callback) {
    var ganttObject;
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "get_gantt.php",
        data: {request_number: requestNumber},
        success: function(returnValue){
            callback(returnValue);
        }
    });
}

$(function() {

    var requestNumber = $('#request_number').text();

    var ganttObject = getGantt(requestNumber, function(ganttObject) {
        console.log(ganttObject);
    });

});

Btw, I've also removed this parseJSON stuff - setting dataType to json does the job and is less dirty.

I know why it's not returning it at least. The ganttObject may be in the same scope, but the success function is ultimately running in the readyState callback from the XMLHTTP object, so it's on a different thread than the getGantt function. Can you make the $(function(){... code apart of your success function?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top