We create an input text and button to facilitate users to search tutorials. Also we create a list to display the search results. <body> <div id="container"> <input type="text" id="search"/> <input type="button" id="button" value="Search" /> <ul id="result"></ul> </div> </body> =============================================================== JavaScript
We specify so that when users click button or press enter key the process of searching data begins. Here we use click and keyup event. As usual we use ajax function to perform data change in the background.To limit when users input nothing but click the button or press enter, we create simple checking using if.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ function search(){ var title=$("#search").val(); if(title!=""){ $("#result").html("<img alt="ajax search" src='ajax-loader.gif'/>"); $.ajax({ type:"post", url:"search.php", data:"title="+title, success:function(data){ $("#result").html(data); $("#search").val(""); } }); } } $("#button").click(function(){ search(); }); $('#search').keyup(function(e) { if(e.keyCode == 13) { search(); } }); }); </script> ====================================================== Database configuration file used in this tutorial. Adjust the server location, username, password and database name
file : db.php <?php mysql_connect("localhost","user","password") or die("error koneksi"); mysql_select_db("database_name") or die("error pilih db");?> ========================================================= This is the code that searchs articles based on the user input and brings the results in ajax search way.Once again we performs checking using if to ensure when no data found it will give an output “No Tutorial Found”
file : search.php <?php include "db.php"; $title=$_POST["title"]; $result=mysql_query("SELECT * FROM wp_posts where post_title like '%$title%' and post_status='publish'"); $found=mysql_num_rows($result); if($found>0){ while($row=mysql_fetch_array($result)){ echo "<li>$row[post_title]</br> <a href=$row[guid]>$row[guid]</a></li>"; } }else{ echo "<li>No Tutorial Found<li>"; } // ajax search?> ==================================================================
css
<style type="text/css"> #container{ width:800px; margin:0 auto; } #search{ width:700px; padding:10px; } #button{ display: block; width: 100px; height:30px; border:solid #366FEB 1px; background: #91B2FA; } ul{ margin-left:-40px; } ul li{ list-style-type: none; border-bottom: dotted 1px black; height: 50px; } li:hover{ background: #A592E8; } a{ text-decoration: none; font-size: 18px; } </style>
No comments:
Post a Comment