0

I have a function that is called to create a row in a table with row data being passed in. Within that function I need to call an AJAX function to retrieve data related to one of the cells in the row. While I get the variable via the .done method I'm struggling to see how to make it available in the fctn1 function.

function fctn1( rowdata ) {
  var url = "https://...";
  var state;
  fetchData(url).done(function(data) {
    var state = data.items.state;
    console.log(state);    // logs correct state
  });
  console.log(state);    // undefined
    // fctn1 code creates table row using rowdata and 'state' variable from AJAX call
}

function fetchData(url) {
  // Return the $.ajax promise
  return $.ajax({
    url: url,
    type: "GET",
    contentType: "application/json",
    dataType: 'json',
  });
}
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
joe862
  • 1
  • Short answer is call your function from inside the `done` where you have the `state`. Linked duplicate goes in to more detail – Jamiec Sep 29 '17 at 08:15
  • I thought about that and read the link but wasn't sure how to achieve this. The outer function, fctn1, has the row data passed in and returns the HTML with `state` variable included. The row data is needed to determine the AJAX URL so can't call fctn1 from inside `done` as URL is not determined. – joe862 Sep 29 '17 at 09:16
  • Sorry, what I should have said is - build your table row using `rowdata` and `state` from within the `done`. Only there do you have access to both the variable passed in, and the response from your ajax call. – Jamiec Sep 29 '17 at 09:48
  • thanks it working now, yip needed to wrap the row method calling fctn1 into the `done`, sorted thanks for the steer.. – joe862 Sep 29 '17 at 10:02

0 Answers0