1

I have this situation, a form where the user sets the date and a number of days so I can calculate a dead line date via javascript methods. I found an api that return json objects with the holidays in my city. the problem is, when I call my method passing a date that I know that is a holiday and it is present in the json object, the method returns false. If I copy and paste the method line by line on chrome's dev tool, it return true. what am I missing?

OBS: the date format used in my country is dd/mm/YYYY, that's why I use some date formatting and to compare with the dates returned in the json objects.

function verifyHoliday(date){
  var url = "https://api.calendario.com.br/?json=true&ano=2018&estado=SP&cidade=MOGI_GUACU&token=ZGdvLmRpZWdvY2FydmFsaG9AZ21haWwuY29tJmhhc2g9MTYzMjcxMDY3";
  var day = (date.getDate() < 10) ? "0"+date.getDate() : date.getDate();
  var dateString = day + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();

  //====================================================
  var holiday = false;
  var holidays = [];
  $.getJSON(url, function(data){
    for(var i = 0; i < data.length; i++){
      var obj = {day: data[i].date, name: data[i].name};
      holidays[i] = obj;
    }
  });

  for(var i = 0; i < holidays.length; i++){
    if(holidays[i].day == dateString){
        holiday = true;
        break;
    }
  }
  return feriado;
}
dgo.carvalho
  • 11
  • 1
  • 2
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hund Nov 20 '18 at 17:24
  • 2
    $.getJSON is asynchronous, meaning the holidays array is filled *after* the code that iterates it is executed. See duplicate question, this is a very common issue – Patrick Hund Nov 20 '18 at 17:25
  • Try loading the full array with the holidays as soon as the page loads, using document.onload, for exemple. – Pedro Lima Nov 20 '18 at 17:30
  • You are padding the day but not the month, so you will get a date like "01/1/2019". Also, you're setting the value of *holiday*, but returning *feriado*. – RobG Nov 20 '18 at 20:16

2 Answers2

0

Try the following code instead - notice the "$.getJSON(url).then(function (data)) {}" instead of your original code.

As someone commented, it appears your issue is due to you using the response before there is an actual response. as $.getJSON is asynchronous.

function verifyHoliday(date){
    var url = "https://api.calendario.com.br/?json=true&ano=2018&estado=SP&cidade=MOGI_GUACU&token=ZGdvLmRpZWdvY2FydmFsaG9AZ21haWwuY29tJmhhc2g9MTYzMjcxMDY3";
    var day = (date.getDate() < 10) ? "0"+date.getDate() : date.getDate();
    var dateString = day + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();

    //====================================================
    var holiday = false;
    var holidays = [];
    $.getJSON(url).then(function (data) {
      for(var i = 0; i < data.length; i++){
        var obj = {day: data[i].date, name: data[i].name};
        holidays[i] = obj;
      }
    });

    for(var i = 0; i < holidays.length; i++){
      if(holidays[i].day == dateString){
          holiday = true;
          break;
      }
    }
    return feriado;
  }
Mikkel
  • 1,853
  • 1
  • 15
  • 31
0

There are a few issues with your code:

  1. The call is asynchronous and you aren't waiting for the response
  2. You're formatting dates as DD/M/YYYY, so the comparison will fail for single digit months
  3. You haven't declared or initialised feriado so you should get a reference error

Here's a quick example testing if new year's day is a holiday:

var req = new XMLHttpRequest();
req.onload = function(e) {
  var text = req.response;
  var data = JSON.parse(text);
  var holidays = data.map(hol => ({day:hol.date, name:hol.name}));
  var nyd = '01/01/2018';
  console.log(`Is ${nyd} a holiday? ${holidays.some(hol => hol.day == nyd)}`);
}

var url = 'https://api.calendario.com.br/?json=true&ano=2018&estado=SP&cidade=MOGI_GUACU&token=ZGdvLmRpZWdvY2FydmFsaG9AZ21haWwuY29tJmhhc2g9MTYzMjcxMDY3'
req.open('GET', url); // async request
req.responseType = 'text';
req.send();

PS

You should only do the request once and store the result as running it on every call to verifyHoliday is very inefficient. It's likely that holidays don't change very often (they're usually gazetted years in advance) so even once per day is more than enough.

RobG
  • 142,382
  • 31
  • 172
  • 209