20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryのAjaxでリアルタイム検索のやつ

Last updated at Posted at 2016-01-15

ありがちなやつです。
備忘録的な感じで書いてます。

index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>

<h1>Search our Phone Directory</h1>
<form id="searchform" method="post">
<div>
	<label for="search_term">Search name/phone</label>
  	<input type="text" name="search_term" id="search_term" />
  	<input type="submit" value="search" id="search_button" />
    </div>
</form>
<div id="search_results"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
    $("#search_button").click(function(e){
        e.preventDefault();
        ajax_search();
    });
    $("#search_term").keyup(function(e){
            e.preventDefault();
            ajax_search();
        });

});
function ajax_search(){
  $("#search_results").show();
  var search_val=$("#search_term").val();
  $.post("./find.php", {search_term : search_val}, function(data){
   if (data.length>0){
     $("#search_results").html(data);
   }
  })
}
</script>
</body>
</html>
find.php
<?php
define(HOST, "xxx");
define(USER, "xxx");
define(PW, "xxxx");
define(DB, "xxx");

$connect = mysqli_connect(HOST,USER,PW) or die('Could not connect to mysql server.' );
mysqli_select_db($connect,DB) or die('Could not select database.');
mysqli_set_charset($connect, "utf8");

$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysqli_real_escape_string($connect,$term);

$sql = "SELECT member_name,member_phone FROM members where member_name like '%$term%' or member_phone like '%$term%' order by member_name asc";
$result = mysqli_query($connect,$sql);

$string = '';

if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    $string .= $row['member_name']." - ";
    $string .= $row['member_phone'];
    $string .= "<br/>\n";
  }

}else{
  $string = "No matches!";
} 

echo $string;

簡単ではありますが、こんなもんで勘弁して下さい。

20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?