document.getElementById('button1').addEventListener('click', loadCustomer);
document.getElementById('button2').addEventListener('click', loadCustomers);
// Load Single Customer
// Create a function named LoadCustomer and passing the Event Object
function loadCustomer(e){
const xhr = new XMLHttpRequest();
xhr.open('GET', 'customer.json', true);
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
const customer = JSON.parse(this.responseText);
const output = `
<ul>
<li>ID: ${customer.id}</li>
<li>Name: ${customer.name}</li>
<li>Company: ${customer.company}</li>
<li>Phone: ${customer.phone}</li>
</ul>
`;
document.getElementById('customer').innerHTML = output;
}
}
xhr.send();
e.preventDefault();
}
// Load Customers
function loadCustomers(e){
const xhr = new XMLHttpRequest();
xhr.open('GET', 'customers.json', true);
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
const customers = JSON.parse(this.responseText);
let output = '';
// We can't just output the data, we need to loop through
customers.forEach(function(customer) {
output += `
<ul>
<li>ID: ${customer.id}</li>
<li>Name: ${customer.name}</li>
<li>Company: ${customer.company}</li>
<li>Phone: ${customer.phone}</li>
</ul>
`;
});
document.getElementById('customers').innerHTML = output;
}
}
xhr.send();
e.preventDefault();
}
Leave a Reply