Utilizzare ajax e PHP per realizzare una ricerca in tempo reale!

Posted on 20. Nov, 2009 by daniele in ajax, php, tutorials


In questo tutorial useremo jQuery per eseguire una ricerca su una tabella MySQL, senza attendere il caricamento di una nuova pagina. Prima di tutto costruiremo il documento PHP che sarą utilizzato da jQuery per eseguire la ricerca e poi ci occuperemo di realizzare la parte html per rendere l'interfaccia user-friendly.

 
$link = mysql_connect("localhost","root","");
mysql_select_db("td_search", $link);
 
$keywords = mysql_real_escape_string( $_POST["keywords"] );
 
$query = mysql_query("SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%". $keywords ."%' && `post_status` = 'publish'");
 
$arr = array();
while( $row = mysql_fetch_array ( $query ) )
{
	$arr[] = array( "id" => $row["ID"], "title" => $row["post_title"], "content" => $row["post_content"] );
}
 
echo json_encode( $arr );
 
 
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 
<title>TutDepot Search Demonstration</title>
 
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>
 
<script type="text/javascript">
	$(document).ready(function(){
		$(".search").click(function(){
			$.post("search.php", { keywords: $(".keywords").val() }, function(data){
				$("div#content").empty()
				$.each(data, function(){
					$("div#content").append("- <a href='post.php?id=" + this.id + "'>" + this.title + "</a>");
				});
			}, "json");
		});
	});
</script>
 
</head>
 
<body>
<input type="text" name="search" class="keywords"/>
<input type="submit" name="submit" class="search"/>
<div id="content">
</div>
 
</body>
</html>
 

Correlati

Leave a reply