I have a Json array, that I'm parsing into a javascript object array.
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function() {
var data = JSON.parse(request.responseText);
// renderhtml(data);
addPerson(data);
};
request.send();
});
I have made an addPerson function to add a user-defined object into the list.
addPerson = (data) => {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var age = document.getElementById("age");
var id = data.pop()+1;
const person = {fName, lName, age, id};
data.add(person);
}
when the function is called I get 'addPerson is not defined' as an error. Why is this?
here is my entire file:
var btn = document.getElementById("btn");
var root = document.getElementById("root");
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function(){
var data = JSON.parse(request.responseText);
//renderhtml(data);
addPerson(data);
};
request.send();
});
renderhtml = (data) => {
let htmlString = " ";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + data[i].lName + "</p>"
}
addPerson = (data) => {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var age = document.getElementById("age");
var id = data.pop()+1;
const person = {fName, lName, age, id};
data.push(person);
}
root.insertAdjacentHTML('beforeend', htmlString);
}
addPerson()is defined in a scope such that it's not accessible from the XHR callback. Without seeing more code it's impossible to be more precise.