0

How do I make this js function work? The log shows "forwarded", but the forward value is still 0.

   function getDayForward(day, time) {
      var product_id = {!! json_encode($product->id ?? null) !!};
      var daysEnabled = {!! json_encode($days_available ?? null) !!};
      var forward = 0;
      $.ajax({
        url: '/products/' + product_id + '/days/' + day + '/times/values',
        method: 'GET',
        success: function(data) {
          for(let j = 0; j < data.value.length; j++) {
            if (time == data.value[j]) {
              // If no time available, the day will be forwarded
              if(j == data.value.length - 1) {
                console.log('forwarded');
                for (let k = 0; k < daysEnabled.length; k++) {
                  if(daysEnabled[k] == day) {
                    if(k == daysEnabled.length - 1) {
                      forward = 7 - daysEnabled[k] + daysEnabled[0];
                      // console.log(forward);
                    } else {
                      forward = daysEnabled[k + 1] - daysEnabled[k];
                      // console.log(forward);
                    }
                  }
                }
              } else {
                console.log('not forwarded');
              }
            }
          }
        }
      });
      return forward;
    }

I want to access the forward value as the return from getDayForward function.

Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
  • This is the fundamental mistake many people make when trying to get their head around Ajax, or any other delayed response. Your problem is that the `return` statement runs _before_ the response is available (the `success` property). Ajax sends the request, returns immediately, and, later, when the response is available, runs the additional code. I have no idea what you want to do with the `forward` variable, but whatever it is, you need to do it as part of the `success` property. – Manngo May 27 '20 at 01:08
  • If you’re doing this as a learning exercise, fine. If you’re trying to use use ajax seriously, all modern browsers support the `fetch` API, which is simpler to work with. Forget using jQuery for this: it’s an unnecessary distraction. – Manngo May 27 '20 at 01:10
  • Oh I see, thank you sir for the reply, I will try to solve as the clue you mentioned. – Farhan Muhammad May 27 '20 at 01:10
  • Exactly I just learned JS for a week. Thank you for your suggestion, I will try it. – Farhan Muhammad May 27 '20 at 01:12

0 Answers0