1

I used this example to hopefully return data after an AJAX call. Basically I execute the AJAX calling a callback function that process and returns the desired final data. However, when I execute the code the variable assigned to get the data is undefined and the callback function is correctly executed AFTER....

This is the function that executes the AJAX call:

    function getgraphdata(callback){
    $.ajax({
        type: "GET",
        url: "DiCAST_hourly.csv",
        dataType: "text",
        async: false,
        success: callback,
        error: function(){alert("Error")}
        });
};

This is the callback function:

function processgraphData(allText) {
    var result = [];
    var allTextLines = allText.split(/\r\n|\n/);
    for (var i=1; i<allTextLines.length; i++) {
        if (allTextLines[i].split(",")[0] == 'LETO') {
            var line = allTextLines[i].split(",");
            for (var j = 1; j<line.length - 5; j += 5){
                result.push([line[j],line[j+1],line[j+2]]);
            };
            break;
            };
        };
    console.log("OK");
    console.log(result);
    return result;
    };

These are the lines where I execute this code:

      console.log("OKOK");
      var result = getgraphdata(processgraphData);
      console.log(result);
      console.log("OKOK");

And this is what the browser returns:

 OKOK getinfo.js:135
 OK getinfo.js:86
[Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3]] getinfo.js:87
undefined getinfo.js:137
OKOK 
Community
  • 1
  • 1
Rafa
  • 2,879
  • 2
  • 21
  • 27

1 Answers1

0

This would resolve your issues:

function getgraphdata(callback){
    var theresponse;
    $.ajax({
        type: "GET",
        url: "DiCAST_hourly.csv",
        dataType: "text",
        async: false,
        success:function(response){     
        theresponse = processgraphData(response);
        },
        error: function(){alert("Error")}
        });
    return theresponse;
Rafa
  • 2,879
  • 2
  • 21
  • 27
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44