EXERCISE: AJAX GET AND FILTER

Posted on

This exercise you will learn on how to get the data using AJAX GET and use JQuery filter. JQuery filter allow you to filter the data inside the element for example DIV or TABLE. This help user to search specific item. The result as in the video below:

HTML for this exercise:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Filter and AJAX</title>
<style media="screen">
img {
  height:100px;
  width:100px;
  object-fit:cover;
}
input {
  width: 100%;
  height: 50px;
}
</style>
</head>
<body>
  <input type="text" name="" value="" placeholder="Filter data" id="dessertinput">
  <div class="dessert" id="dessert">

  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="script-solution.js" charset="utf-8"></script>

</body>
</html>

For this exercise, use below URL to get the data.

https://adisazizan.xyz/tutorial/api/dessert.php

Solution:

$.get("https://adisazizan.xyz/tutorial/api/dessert.php", function(data){
var a = '';
for (var i = 0; i < data.length; i++) {
a += "<div><h1>" +data[i]["dessert"]+ "</h1><img src='" +
data[i]["imgurl"]+"'> <p>"+data[i]["about"]+"</p></div>";
}
document.getElementById("dessert").innerHTML = a;
});

$("#dessertinput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$(".dessert div").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *