I'm building an employee directory using AJAX/jQuery leveraging the Random User Employee Directory API. This is the actual data feed i'm using:
https://randomuser.me/api/?results=12&format=json
I have successfully retrieved and displayed a page full of sample employees. But I'm having an issue in showing an individual's record (via modal) if a user clicks on a record. Console log is saying "Cannot read property 'cell' of undefined". I'm pretty confident that this is due to the displayModal function not being able to access the data from the json call in the 'employees' variable. I've tried moving that function inside of the $ajax call where I'm retrieving the data, but that doesn't work--so not sure where to go from here.
//Get JSON DATA and stored data in variable Employees.
var employees;
$.ajax({
url: 'https://randomuser.me/api/?results=12&format=json',
success: function(data){
employees = data.results;
displayEmployees(employees);
console.log(employees);
}
});
//Create Function to Build Employee Car
function displayEmployees(employees){
var employeesHTML = ""
$.each(employees, function(i, employee) {
employeesHTML += '<div class="employee" employee-id="' + employee.id.value + '>';
employeesHTML += '<a href="">';
employeesHTML += '<img class="employee-photo" src="' + employee.picture.large + '"></a>';
employeesHTML += '<div class="info">';
employeesHTML += '<div class="name">'+ employee.name.first + ' ' + employee.name.last + '</div>';
employeesHTML += '<div class="email grey-font">'+ employee.email + '</div>';
employeesHTML += '<div class="city grey-font">' + employee.location.city + '</div></div></div>';
});
$('.employees').html(employeesHTML);
};
//Create Function to Build Modal
function displayModal(employees, id){
var employeesModal;
//create modal
employeesModal += '<div>' + employees[id].cell + '</div';
$('.modal-text').html(employeesModal);
}
//Click Event To Display Modal
var modal = document.getElementById('myModal');
$('.employees').on("click", ".employee", function() {
$.each(employees, function(i, employee) {
var id = $(this).attr('employee-id');
modal.style.display = "block";
displayModal(employees, id);
console.log('click');
});
});
// // When the user clicks on (x), close the modal
$('.close').on("click", function() {
modal.style.display = "none";
});
// // When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
console.log(employees);
var id = $(this).attr('data-id');is returningNaNso it cannot find the employee by index becauseNaNwon't workdatamethod: api.jquery.com/dataparseInt(id)because values coming out of the DOM are always strings