I have included a search bar in my wordpress site using html, css, php and js code to parse and extract data from a two-column csv file. The data is text: first column, company stock ticker; second column, company name. The livesearch works and displays matching data in the browser console but fails to display it in a drop down menu beneath the search bar. Instead the conditional logic in the js file reports that:
Received data: {success: true, data: Array(9)}
HR_livesearch.js?ver=1.0.0:14 Type of data: object
HR_livesearch.js?ver=1.0.0:15 Data length: N/A
HR_livesearch.js?ver=1.0.0:36 No data to display, hiding results.
HR_livesearch.js?ver=1.0.0:12 Received data: {success: true, data: Array(1)}
HR_livesearch.js?ver=1.0.0:14 Type of data: object
HR_livesearch.js?ver=1.0.0:15 Data length: N/A
HR_livesearch.js?ver=1.0.0:36 No data to display, hiding results.
Here is the js code I am using:
document.addEventListener('DOMContentLoaded', function() {
console.log("DOMContentLoaded event triggered.");
const searchBox = document.getElementById('liveSearchBox');
const resultsDiv = document.getElementById('searchResults');
searchBox.addEventListener('input', function() {
const searchText = this.value;
if (searchText.length > 1) {
fetch(tickerSearchData.ajaxurl + '?action=perform_live_search&search=' + encodeURIComponent(searchText))
.then(response => response.json())
.then(responseObject => {
console.log("Received data:", responseObject); // Confirming the received data structure
if (responseObject.success) {
console.log("Success flag is true.");
// Directly working with the data array
let data = responseObject.data;
if (data && Array.isArray(data) && data.length > 0) {
console.log("Data array is present and has length:", data.length);
resultsDiv.innerHTML = ''; // Clear previous results
resultsDiv.style.display = 'block'; // Ensure results div is shown
const ul = document.createElement('ul');
data.forEach(item => {
const li = document.createElement('li');
li.textContent = item; // Assuming 'item' is directly usable as text
ul.appendChild(li);
});
resultsDiv.appendChild(ul);
} else {
console.log("Data array is empty or not present.");
resultsDiv.style.display = 'none'; // Hide results div if no data
}
} else {
console.log("Success flag is not true.");
resultsDiv.style.display = 'none';
}
})
.catch(error => {
console.error('Fetch error:', error);
resultsDiv.style.display = 'none';
});
} else {
resultsDiv.style.display = 'none';
}
});
});
I’ve replaced the dynamic segment with static data and the drop down menu appears with the expected list of static data items. There’s something in the dynamic conditional logic that is failing to recognize the presence of data in the array and I am at a loss as to what it might be. I am new to this, so forgive me if the answer is elementary.