0

I'm able to parse an item in a Json array inside of an AJAX request, but outside it comes undefined. Why is this?

function samplesByDate() {
  var csrftoken = getCookie('csrftoken');
  $.ajax({
        url : "/samples/byDate/",
        type : "POST",
        data : { csrfmiddlewaretoken : csrftoken },
        success : function(json) {
      if (json['error'] === 'true' ) {
        alert(json['message']);
      } else {
        console.log(json['samples']);
        return json['samples'];
      }
    },
    error : function(xhr,errmsg,err) {
    console.log(xhr.status + ": " + xhr.responseText);
    }
  })
};

The console log inside the ajax function reports correctly:

[
    {
        "id": 72, 
        "title": "Sample Upload 1", 
        "date": "2017-09-18", 
        "coordinates": "45.58837890625, -122.39273834228516", 
        "type_primary": "Brix", 
        "value_primary": 15.52022647857666, 
        "type_secondary": "Dry Matter", 
        "value_secondary": 16.35165786743164
    }
]

But when I attempt to print the value after its been returned, its instead undefined.

console.log(samplesByDate());

With a console display of

undefined

One thing I've noted is that its not erroring that samplesByDate() is undefined, so its correctly iterating through the function, but rather display undefined in an attempt to print the return value.

Bentaye
  • 9,403
  • 5
  • 32
  • 45
Hikalea
  • 119
  • 2
  • 10
  • 1
    That's because the call is asynchronous, and when you try to print it outside success, the ajax request hasn't finished yet therefore haven't returned your json yet, promises or $.Deferred 's are your friends in this case – Lixus Oct 12 '17 at 17:47
  • `samplesByDate` does not have a `return` statement. The `success`-property function does have a `return` statement, but that code is not run until some time in the future, after `samplesByDate` has already terminated. – apsillers Oct 12 '17 at 17:52
  • I see how promises is the way to go, allowing the engine to await a response before terminating the function; but I'm having trouble wrapping my head around how to implement it. Should samplesByDate() be wrapped in another function? or should the use of promises invoke samplesByDate()? Thanks a ton guys. – Hikalea Oct 12 '17 at 18:00
  • @Hikalea: `samplesByDate` should return a promise. The duplicates show exactly what to do. – Felix Kling Oct 12 '17 at 18:14

0 Answers0