Skip to content

Instantly share code, notes, and snippets.

@ariakm25
Last active July 28, 2019 11:49
Show Gist options
  • Save ariakm25/14d29e05b825866dc965d7f8209f0a89 to your computer and use it in GitHub Desktop.
Save ariakm25/14d29e05b825866dc965d7f8209f0a89 to your computer and use it in GitHub Desktop.
Ajax Search with XHR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>XHR Search</title>
</head>
<body>
<input type="text" name="s" id="search" onkeyup="ajaxSearch(this.value)" />
<div id="hasil"></div>
<script>
function ajaxSearch(val) {
let index = val.length
var ajax;
if (window.XMLHttpRequest)
ajax = new XMLHttpRequest();
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");
if (index % 3 == 0) {
document.getElementById("hasil").innerHTML = ``;
ajax.onreadystatechange = function () {
if (ajax.status == 200 && ajax.readyState == 4) {
let res = JSON.parse(ajax.response).results
for (let index = 0; index < res.length; index++) {
document.getElementById("hasil").innerHTML += `<h1>${res[index].title}<h1>`;
}
}
}
ajax.open("GET", `https://api.jikan.moe/v3/search/anime?q=${val}&limit=5`, false);
ajax.send();
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment