You can't display search results on the same page using window.location
, that
takes you to another page. In this case, you probably want to use a
XHR request to
get the data and then display it on the same page.
I've modified the HTML a little:
<form id="search-form">
<label>Search blog: <input class="mb0" type="search" id="search-query"></label><input type="submit" value="Search">
</form>
<ul id="search-results"></ul>
Then in list.php you would do something like this:
<?php
// get the q parameter that we will be setting in our XHR request
$query = isset($_GET['q']) ? $_GET['q'] : '';
// I'm assuming you are returning a list of links, so I'm creating an
// array of associative arrays that contain url and link name info.
// In your actual application you would probably be pulling this data from a
// database instead, using the $query variable to filter the results that the DB
// returns. I would recommend using prepared statements to avoid SQL injection
// attacks. My PHP is really rusty right now so I'm not going to attempt to
// filter this array and just return the whole thing.
$results = array(
array('name' => 'Foo', 'url' => '/foo'),
array('name' => 'Bar', 'url' => '/bar'),
array('name' => 'Baz', 'url' => '/baz'),
);
// encode our array as JSON so we can easily decode it in JavaScript
echo (json_encode($results));
?>
Then, here is the JS you would use to make the request and display the results.
// cache elements we will be using in variables
const searchForm = document.getElementById("search-form");
const searchQuery = document.getElementById("search-query");
const searchResults = document.getElementById("search-results");
// this function will do the XHR request and display the results
function blogSearch(event) {
// stops the default action, in this case submitting the form to the server
event.preventDefault();
// get the query and build a url to request
let query = searchQuery.value;
let url = `../list.php?q=${query}`;
let displayError = () => {
searchResults.innerHTML = '<li>There was an error retrieving your search results</li>';
};
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => {
if (this.status >= 200 && this.status < 400) {
// parse the JSON data that was returned
let data = JSON.parse(this.response);
// build up a list of li element containing links
let html = ''
data.forEach(item => {
html += `<li><a href="${item.url}">${item.name}</a></li>`;
});
// display the search results in our unordered list
searchResults.innerHTML = html;
} else {
displayError();
}
};
request.onerror = () => {
displayError();
};
request.send();
}
// attach the event to the search form
searchForm.addEventListener('submit', blogSearch, false);
A few notes on things I changed:
Further reading