user4683088
user4683088

Reputation:

JavaScript function can't be called twice

The following function creates a table based on the data received from an API request. It can be called successfully the first time, but any calls afterward result in

Uncaught TypeError: contact.src is not a function at HTMLButtonElement.onclick

The function:

let contact = {
  src: function () {
    let rawdata = new FormData(document.querySelector('#SrcContactForm'))
    let data = new FormData()
    data.append('FieldOne', rawdata.get('FindFieldOne'))
    fetch('http://sub.domain.tld/api/v1/contacts/search', {
      method: 'post',
      body: data,
      headers: {
        'Auth-Token': getCookie('Auth')
      }
    })
      .then((resp) => resp.json())
      .then(function (data) {
        console.log(data)
        if (data.success !== true) {
          notif.show('Contacts could not be found.', 'red')
        } else {
          notif.show('Contacts successfully found.', 'green')
          let table = document.createElement('table')
          table.id = 'SrcContactTable'
          table.setAttribute('class', 'table table-bordered table-responsive')
          let thead = document.createElement('thead')
          thead.class = 'text-primary'
          let th1 = document.createElement('th')
          th1.innerHTML = 'ID'
          thead.appendChild(th1)
          table.appendChild(thead)
          for (contact in data.result) {
            let tr = document.createElement('tr')
            tr.id = data.result[contact]['ID']
            let td1 = document.createElement('td')
            td1.innerHTML = data.result[contact]['ID']
            tr.appendChild(td1)
            table.appendChild(tr)
          }
          document.getElementById('table-responsive').appendChild(table)
        }
      })
      .catch(function (error) {
        console.log('Request failed', error)
      })
  }
}

Changing from let to var doesn't make a difference. When you remove the following line, the function can be called as many times as wanted:

let table = document.createElement('table')

But then a table isn't created, which defeats the purpose of the function.

Upvotes: 0

Views: 254

Answers (1)

Quentin
Quentin

Reputation: 944320

You're overwriting your contact variable in your for loop:

var contact = {
  src: function() {
    for (contact in contact.data) {
      console.log(contact);
    }
  },
  data: {
    foo: 1,
    bar: 2,
    baz: 3
  }
};

contact.src();
console.log("Final value", contact);

Use a local variable with var or let and a different name:

var contact = {
  src: function() {
    for (let c in contact.data) {
      console.log(c);
    }
  },
  data: {
    foo: 1,
    bar: 2,
    baz: 3
  }
};

contact.src();
console.log("Final value", contact);

Upvotes: 2

Related Questions