Search code examples
phpjqueryarraysjsonajax-request

I receive correct data from JSON request but when I want to return the result from the function I get "undefined"


When I call this function, I receive the correct array that I want, but once I try to return it the console tells me that "options" is undefined. Any ideas?

function getOptionsJSON(Ordernumber) {

    $.getJSON(window.location.pathname+'/ajaxRequest?ordernumber='+Ordernumber+'&'+Math.round(new Date().getTime()), function(data) {
        if(data['articleID']) {
            options = data['values_label_array'];   
            console.log(options)    // returns {"1":"Option 1","2":"Option 2"}
            }       
    });
    console.log(options) // returns Undefined
    return options;     
}


function selectOptions(){
    var options = getOptionsJSON($(row).find('.ordernumber').val());
    console.log(options)     //  returns Undefined  
}

This is the PHP function that is called in the AjaxREquestAction:

$returnData["values_label_array"] = json_encode($this->getOptionsAction($ordernumber)); 

Solution

  • The problem is that getJSON is asynchronous.

    console.log(operations) is executing before the JSON request has actually been completed. You can see this in the console.log where the undefined line will appear above the options.

    Inside function(data) you need to call a processor instead of having the getOptionsJSON return options.

    You could do this simply by

    $.getJSON(window.location.pathname+'/ajaxRequest?ordernumber='+Ordernumber+'&'+Math.round(new Date().getTime()), function(data) {
        if(data['articleID']) {
            options = data['values_label_array'];   
            console.log(options)    // returns {"1":"Option 1","2":"Option 2"}
            processJSON(options );
         }       
    });
    
    function selectOptions(){
        getOptionsJSON($(row).find('.ordernumber').val());
    }
    
    function processJSON(data) {
       //do something with the JSON;
    }