Farkas Tamas
Farkas Tamas

Reputation: 21

Undefined variable in jquery's ajax call

I have a relatively simple code, I am annding event listeners in a loop, but the loop variable is not available when mapping the results.

for (let index = 0; index < 2; ++index) {
    $("#id" + index).on("keyup", function () {

        $.ajax({
                type: "GET",
                url: "https://some-url.com",
                dataType: "json",
                success: function (data) {
                    $('#div' + index).append(
                        $.map(data, function (myData, index) {
                            return '<a href="#" onclick="selectId(index, myData.id);"> Click me </a>'
                        }).join());
                }
            }
        );
    });
}

The result is: Uncaught ReferenceError: index is not defined

Edit: if I just use myData.id for example, everything works like a charm Any ideas what am I missing here?

Upvotes: 2

Views: 148

Answers (1)

Quentin
Quentin

Reputation: 944498

You are generating strings of HTML with embedded JS. The JS won't be evaluated until it is inserted in the document. That's a different scope with no index or myData variables.

Generate a jQuery object instead. And if you don't want to link anywhere, don't use a link!

 function (myData, index) {
     const $button = $("<button />")
     $button.text("Click me");
     $button.on("click", () => selectId(index, myData.id));
     return $button;
 }

(And don't join the array into a string, just append the array of jQuery elements).

Upvotes: 1

Related Questions