0

I have an Jquery Ajax call like so:

$('body').on('click', '#btnPopulate', function() {
alert(getTree());
});


function getTree() {
var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewModel";
$.ajax({
    type: "POST",
    cache: false,
    url: url,
    success: function (result) {
        if (result.success === true) {
            var data = result.data;
            return data;
        } else {
            return null;
        }
    },
    error: function (responseText, textStatus, errorThrown) {
        alert('Error - ' + errorThrown);
    }
});
}

When I click the button, the alert box just says 'undefined', as if there is no data being returned But in the ajax call, the "var data = result.data" has loads of data in it when I breakpoint it. So why is this not being returned to the alert box? The data being returned is an array of objects, with each object further containing an array of objects. But the data is definitely being returned from the controller to "var data".

ailinmcc666
  • 413
  • 5
  • 15
  • what is result? because in the success: function(result) it is not an object, and you're treating it as an object. if it's json try `var resultobj = $.parseJSON(result);` – Cr1xus Mar 13 '17 at 15:46

2 Answers2

0

There first call to alert, tires to alert the value returned by getTree. Since getTree has no defined returned value, it returns undefined to the first alert call.

This is why you see 'undefined' in the alert box initially.

Try calling alert from within your Ajax call success callback instead of on the click handler:

$('body').on('click', '#btnPopulate', function() {
  getTree(); 
}); 
function getTree() { 
  var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewModel"; 
  $.ajax({ 
    type: "POST", 
    cache: false, 
    url: url, 
    success: function (result) { 
      if (result.success === true) { 
        var data = result.data; 
        alert(data); 
      } else { 
        return null; 
      } 
    }, 
    error: function (responseText, textStatus, errorThrown) { 
      alert('Error - ' + errorThrown); 
    } 
  }); 
}
Pineda
  • 7,435
  • 3
  • 30
  • 45
0

It sounds like you're having trouble understanding AJAX in general, when you call alert(getTree()) it's returning what getTree() returns... not the AJAX call.

Your return data; is actually a return for the success handler in your AJAX call itself. So if you were to place the alert(data); there, when the AJAX call is finished then the alert will show with the correct data.

Patrick Barr
  • 1,123
  • 7
  • 17