Tìm kiếm bằng Ajax

Cũng lâu rồi không viết bài viết nào. Hôm này tự nhiên có cảm giác lại chắc là do, có động lực gì đó. Trong bài viết này mình xin hướng dẫn các bạn tạo một công cụ tìm kiếm trong website, cũng như các bạn thường thấy

trên các website khác và làm sao người ta làm được như vậy, Thì hôm này tôi xin hướng dẫn các bạn một số kỹ thuật nhỏ này để làm cho website của bạn linh động hơn và mát mắt hơn.

Đầu tiên bạn tạo cho tôi bố cục càc file giống như dưới đây:

   config/dbcon.php

   class/sanpham.class.php

   timkiem.php( nằm cùng cấp với 2 thư mục trên)

   index.php( nằm cùng cấp với 2 thư mục trên)

Sao khi các bạn tạo xong các bạn hãy copy các đoạn code bên dưới vào cho từng file.

code file dbcon.php file này dùng để các thành phần kết nối CSLD


<?php
$db_local="localhost";
    $db_user="root";
    $db_pass="";
    $db_database="hocphp";

?>

code file sanpham.class.php file này chúng ta dùng để truy xuất và thực thi các câu lệnh tương tác với CSDL trong xampp,...

class Sanpham{
        public $connect;
        private $user;
        private $pass;
        private $local;
        private $data;
        public $result;
        public $sql;
        public $result_query=null;
        public $error=array();

       public function __construct() {
            include 'config/dbcon.php';
            $this->local = $db_local;
            $this->user = $db_user;
            $this->pass = $db_pass;
            $this->data =$db_database;
            $this->connection();
        }
        public function connection(){
            //echo $this->local;
            $this->connect=mysql_connect($this->local,$this->user,$this->pass);
            if(isset($this->connect)){
                mysql_select_db($this->data,$this->connect);
                mysql_query("set names 'utf8'");
                
            }
            else{
                $error="ket noi khong thanh cong";
                echo "ket noi khong thanh cong";
            }
        }
        public function select($sql=NULL){
            if($sql==NULL){
                $this->result_query=mysql_query("select * from dienthoai",$this->connect);    //mặt định lấy table dienthoai
            }
            else{
                $this->result_query=mysql_query($sql,$this->connect);    
            }
                return $this->result_query;

        }

        public function select_count(){
            return mysql_num_rows($this->result_query);
        }
        public function fetch_array_table($result=NULL){
            if($result==NULL)
                if(is_resource($this->result_query))
                        return mysql_fetch_array($this->result_query);
                    return NULL;
        }
}

?>

code file timkiem.php file này dùng để nhận giá trị từ file trang index gửi qua ( ở đây mình sử dụng ajax để gửi giá trị qua file timkiem.php để xử lý)


<?php

 
    include_once('class/sanpham.class.php'); //include file sanpham.class.php

    if(isset($_GET['key']) && $_GET['key']!=""){

        $key=trim($_GET['key']); // nhận giá trị trừ ajax gửi qua để xử lý

        $sql="select * from dienthoai";

        $sql.=" Where tendt like '%$key%'";

        //khoi tao doi tuong sanpham

        $sp = new Sanpham();

        $sp->select($sql);

        if($sp->select_count()>0){

            $str="<ol>";

            while($row=$sp->fetch_array_table()){

                $str.="<li>".$row['tendt']."||gia:".number_format($row['gia'])." đồng</li>";

            }    

            $str.="</ol>";

            echo $str; //trả dữ liệu về file index

        }

        else{

            echo "Khong co san pham nao!";

        }

    }

    else{

        echo "Vui long nhap thong tim kiem";

    }




?>

còn đây là code file index.php của chúng ta

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

    <title>Tim Kiem</title>

    <script type="text/javascript" src="public/js/jquery.1.7.2.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function(){


//khi click vào nút input có id="search" thì thực hiện việc tìm kiếm

            $("#search").on("click",function(){

                 $('#waiting').html("<img src='public/images/loading.gif' style='width:150px;height80px;'/>").fadeIn('fast');  

                $.ajax({

                  type:"get",  //gửi bằng phương thức get

                  url:"timkiem.php",

                  datatype:"text",

                  data:{key:$("#tk").val()},    // lấy giá trị tại input có id="tk"

                  success:function(load_data){

                    $("#waiting").fadeOut("fast"); //đóng loading.gif

                    $(".sp").html(load_data);    //trả về dữ liệu sao khi tìm kiếm xong vào vị trí có class="sp"

                  

                  }


                });

             });

        });

    </script>

    <style type="text/css">

        *{margin: 0px;padding: 0px;}

        #background{width: 600px;margin: 0px auto;font-size: 18px;}

        div.timkiem{margin-top: 100px;width:600px;padding: 5px 5px;

            background-image: url("public/images/timkiem.png");

            background-repeat: no-repeat;height: 300px;

            text-align: center;}

            

        div.timkiem div{padding: 10px 10px;}

        div.form-tk{width: 600px;text-align: center;}

        input#tk{width: 150px;padding: 5px 5px;font-size: 18px;font-family: sans-serif;}

        input#search{padding: 3px 3px;width: 100px;font-size: 18px;}

    </style>

</head>

<body>

<div id="background">

    <div class="timkiem">

        <div class="form-tk">

            

                <div class="k1">

                    <label>Tìm kiếm:</label>

                    <input type="text" name="tk" id="tk" />

                    <input type="submit" name="search" id="search" value="Search"/>

                </div>

            

            <div id="waiting"></div>

        </div>

        <div class="sp-tk">

                

                <div class="sp">

                    

                </div>

        </div>


    </div>

</div>

</body>

</html>

Vậy là xong chúc các bạn làm thành công!

 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)