2

I am trying something simple which is to set a variable to the results of an jquery ajax call which I have set to NON synchronous.

All attempts so far return undefined and I don't know why.

I understand I cannot use a synchronous call as the code would have moved on before the results are returned.

Here's my basic code:

$(document).ready(function() {
    var test = visitorData();
    console.info(test);
});

and the ajax call:

function visitorData() {

var chartValues = [];
var chartLabels = [];

//console.info("chartValues:"+chartValues);
//return "TEST";
$.blockUI({message: '<h1><img src="/img/icons/icon_loading_red.gif" /> Please wait - grabbing data...</h1>'});

$.ajax({
        url: '/visitdata',
        type: 'GET',
        async: false,
        dataType: "json",
        success: function (data) {
            visitors = data;
            console.warn(data);
            for (var k in visitors){
                if (typeof visitors[k] !== 'function') {
                    chartValues.push(visitors[k].average_order);
                }
            }

            console.info(chartValues);
            return chartValues;
        }
    });
}

The values are being obtained in the success function and chartValues exists before the return. But no data is given to the original call.

Not sure why and what I need to do?

Ray
  • 3,018
  • 8
  • 50
  • 91
  • possible duplicate of [jQuery: Return data after ajax call success](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – Ram Oct 07 '13 at 08:11
  • Just found further info in this post http://stackoverflow.com/questions/2195161/how-to-return-an-array-from-jquery-ajax-success-function-properly which I'm working my way through so I think the answer lies there. Will close this question shortly. Sorry for duplicate – Ray Oct 07 '13 at 08:15
  • try to use Fiddler tool to see what is returned from /visitdata – Robert Oct 07 '13 at 08:16

0 Answers0