0

I have a very simple setup:

var genres;
$.get('/api/genres', '', function (response) {
    genres = response.data
}, 'json');
$("#genre").tagit({
    availableTags: genres //this doesn't work
});

For some reason the genres variable is not accessible inside the tagit method. How would I achieve this?

Ortixx
  • 833
  • 3
  • 10
  • 23

1 Answers1

2

$.get is asynchronous. It's not that genres is not accessible inside .tagit. Your problem is that by the time you try to use it, it's still unassigned. A way to fix it would be moving your .tagit function inside the callback:

var genres;
$.get('/api/genres', '', function (response) {
    genres = response.data
    $("#genre").tagit({
        availableTags: genres //this doesn't work
    });
}, 'json');

I also recommend reading $.get's documentation.

William Barbosa
  • 4,936
  • 2
  • 19
  • 37