Search can be implemented with ajax call without causing redirection to the another page. here you can find the example code -
<script>
// Function to make the AJAX call and handle response
function fetchData(query) {
// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Configure the request
xhr.open('GET', 'https://api.example.com/data?q='+query, true);
// Set up a callback function to handle the response
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// Request was successful, parse response
const data = JSON.parse(xhr.responseText);
displayData(data);
} else {
// Request failed
console.error('Request failed. Status:', xhr.status);
}
}
};
// Send the request
xhr.send();
}
// Function to display data on the webpage
function displayData(data) {
const resultDiv = document.getElementById('result');
// Clear previous results
resultDiv.innerHTML = '';
// Create HTML to display fetched data
const dataList = data.results; // Assuming 'results' is an array in the JSON response
dataList.forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.textContent = item.name; // Assuming 'name' is a property of each item
resultDiv.appendChild(itemDiv);
});
}
</script>
for this code to work, you just need to write one API endpoint in your backend solution which will return the search result on API call.
fetchData can be called onclick of seach button, and displayData function will display the results on the page.