jquery Returns the ajax response and the user-defined variable to work

advertisements

I am having an issue passing in a defined variable to a function from an ajax call. What should happen is on click of an element, it should pass the text of the clicked element to the function, do an ajax call which has nothing to do with the defined variable, return the variable and the data from the call to another function that renders the elements. When I get to the function that renders the html content, the variable is now undefined.

My question is how can I send the ajax response data and a user defined variable that has no correlation to the ajax call to another function?

My JSON function:

function getJSONP(url, data) {
  return $.ajax(url, {
    dataType: 'json',
    data: data
  });
}

My click event:

$('.day').on('click', function() {
  getTimes($(this).text());
});

My first function that does the ajax (this is where the selector returns a value):

function getTimes(selector) {
  console.log(selector);
  var eventDate = selector;

  getJSONP(CAL_API_URL).then(function(data) {
    data = _.valuesIn(data)[5][0];
    return data;
  }).then(appendTimes(eventDate));
}

My 2nd function that renders the HTML (here the selector is undefined):

function appendTimes(dates, selector) {
  console.log(selector);

  _.forEach(dates, function(k, v) {
    // Returns each event

    _.forEach(k, function(k2, v2) {
      // Returns multiple objects for each event

      var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
          timeId = k2.id;
      $('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
    });
  });
}


In this case, if you switched appendTimes to only accept selector and have it return a function, the returned function will get called when data is available.

function appendTimes(selector) {
  console.log(selector);
  return function (datas) {
    _.forEach(dates, function(k, v) {
      // Returns each event

      _.forEach(k, function(k2, v2) {
        // Returns multiple objects for each event

        var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
            timeId = k2.id;
        $('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
      });
    });
  }
}