JavaScript: Tìm kiếm sử dụng AJAX

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Hình thức tìm kiếm sử dụng AJAX sẽ cho kết quả hiển thị tự động mỗi khi gõ vào hoặc thay đổi từ khóa tìm kiếm mà không cần phải nhấn nút tìm kiếm hay dùng thao tác khác.

Tổ chức thư mục:

Tổ chức thư mục tìm theo AJAX

Dưới đây là các đoạn code trong các file tương ứng:

File index.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Demo search-AJAX</title>
  <script>
    var xmlhttp;
    function getSearch(a){
      xmlhttp=GetXmlHttpObject();
      null==xmlhttp?alert("Trình duyệt không hỗ trợ HTTP Request"):(xmlhttp.onreadystatechange=stateChanged,xmlhttp.open("GET","getData.php?key="+a,!0),xmlhttp.send(null))
    }
    function stateChanged(){
      4==xmlhttp.readyState&&(document.getElementById("result").innerHTML=xmlhttp.responseText)
    }
    function GetXmlHttpObject(){
      return window.XMLHttpRequest?new XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):null
    }
  </script>
</head>

<body>
  <section>
    <form>
      <section>
        <label>Keyword: </label><input type="search" name="keyword" oninput="getSearch(value);">
      </section>
    </form>
    <hr>
    <section id="result"></section>
  </section>
</body>
</html>

File getData.php:

<?php
  $connect=new MySQLi('localhost','root','','db_c2005l');
  $key=$_GET['key'];
  $sql="select * from product where status and name like '%$key%'";
  $result='';
  $rs=$connect->query($sql);
  if($rs!=null){
    foreach($rs as $item){
      $result.="<section>".$item['name']."</section>";
    }
  }else{
    $result="Không tìm thấy sản phẩm";
  }
  echo $result;
?>

Bạn có thể download source code và database tại ĐÂY.

» Tiếp: HTMLCollection
« Trước: Hàm callback trong JavaScript
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!