0

So I'm having some issues with a function I'm trying to run. Whenever the function is ran, it errors stating it is not a function. I have been through some troubleshooting but still nothing I try seems to work. The function is called every time a button is clicked. I have HTML code to create the button with an onclick event as below:

<button type="button" id="next" onclick="next()">Next Widget</button>

I then have this in my Javascript to run when the button is clicked:

function next() {

  id = 0;

  while (id <= 10) {

    id++;

    function onSuccess(data) {
      var obj = parse.JSON(data);
    }

    var list_URL = BASE_GET_URL + "widgets/" + id + "?username=<username>&password=<password>";

    console.log("Sending GET request for widget");

    $.ajax(list_URL, {
      type: 'GET',
      data: {
        url: url
      },
      success: onSuccess
    });

  }

}

document.getElementById("widgetdescription").innerHTML = obj.data;

The idea is this is suppose to "GET" an image from the API and show it in the "widgetdescription" div. I found online where if you add:

document.getElementById("next").onclick = function () { next() };

This is suppose to fix it, but this does not. Until I get this resolved, I can't find out if my function actually works or not! Any help is much appreciated!

Thanks in advance.

Andy
  • 61,948
  • 13
  • 68
  • 95
S. Lowe
  • 31
  • 4
  • 1
    Please add a runnable code – Danial Aug 21 '21 at 10:38
  • Due to the scoping rules on `onclick` attributes, when JS looks for something called `next` it finds the button with the `id` `next` before it finds any function with the same name. Don't use `onclick` attributes. Do use `addEventListener`. – Quentin Aug 21 '21 at 10:41
  • `document.getElementById("next").onclick = function () { next() };` should fix **that** but then you have to deal with https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Quentin Aug 21 '21 at 10:43
  • Also, when you format the code you notice that `obj.data` will always be `undefined`. – Andy Aug 21 '21 at 10:44

0 Answers0