Created
March 29, 2022 17:12
-
-
Save kdssoftware/f5aa5515f8fad5084baf72f8639f83f7 to your computer and use it in GitHub Desktop.
This example explains how to create search bar with ajax. Built for production
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- | |
@author kdssoftware | |
@created at 3/29/2022 | |
@contact kdssoftware.com | |
Beware: this will only work in practice if you have an api call `/api/search?search=value` set up | |
--> | |
<!-- Optional meta tags --> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> | |
<title>Example search bar</title> | |
</head> | |
<body> | |
<!--The form where the search will be started --> | |
<form method="get" action="" id="searchForm"> | |
<label for="text">Search:</label> | |
<div> | |
<input id="searchTerm" type="text" name="search" value="searchTerm" /> | |
<input type="submit" id="send" name="submit" value="submit" /> | |
</div> | |
</form> | |
<div id="output">Bezig met zoeken...</div> | |
</body> | |
<!--The jquery cdn with ajax, from cdnjs--> | |
<script | |
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" | |
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" | |
crossorigin="anonymous" | |
referrerpolicy="no-referrer" | |
></script> | |
<script> | |
// on first load of the page, check if the search value in the query string is set, if so: fetch the call to search that search term | |
if (new URL(location.href).searchParams.get("search")) { | |
fetchSearch(new URL(location.href).searchParams.get("search")); | |
} | |
// latest timestamp of keyup event. so it does not call the api on every single keyup | |
let lastTimeStampOfTyping = null; | |
document.getElementById("searchTerm").addEventListener("keyup", function (e) { | |
if (e.key === "Enter") { | |
// if the key is enter, it will already be called in the submit event | |
return; | |
} | |
lastTimeStampOfTyping = Date.now(); // update the timestamp | |
setTimeout(function () { | |
//To delay the api call after the user has stopped typing for half a second. | |
if (Date.now() - lastTimeStampOfTyping > 500) { | |
let searchTerm = document.getElementById("searchTerm").value.trim(); | |
//Only fetch the api call when the search term is more than 3 characters, this is only for automatic fetching, the user can still submit the form. | |
if (searchTerm.length > 3) { | |
fetchSearch(document.getElementById("searchTerm").value.trim()); | |
} | |
} | |
}, 500); | |
}); | |
document.getElementById("searchForm").addEventListener("submit", function (e) { | |
e.preventDefault(); // to prevent a page reload, which is a default behavior on submit events in a form | |
fetchSearch(document.getElementById("searchTerm").value.trim()); | |
}); | |
// the function to fetch the api call for searching, it will add the response data to the element with ouput as id | |
function fetchSearch(searchTerm) { | |
document.getElementById("output").innerHTML = "Searching..."; | |
//make call to the api, it returns text/html as content-type | |
$.get("/api/search?search=" + searchTerm, function (data) { | |
// ouput the data in html | |
document.getElementById("output").innerHTML = data; | |
//Make a change to current url, changing its search value to the new search term | |
const url = new URL(location.href); | |
const search_params = url.searchParams; | |
search_params.set("search", searchTerm); | |
url.search = search_params.toString(); | |
const new_url = url.toString(); | |
document.title = "Search for " + searchTerm; | |
window.history.pushState({ html: document.body.innerHTML, pageTitle: document.title }, "", new_url); | |
}); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment