google-like-search

Google like instant search with ajax, JSON & php PDO




Hello Guyz in this post i am going to teach your how to create a google like instant seach with ajax JSON and php PDO. The idea of creating a google like instant search was came from my Gym trainer Aamir bhai Who said me that “Google Search is the best”, So i decided to create a google like search. I have used php PDO for this post because it was a request from a reader of my blog to start teaching new subjects of php like OOP and PDO so i started with PDO



Google like instant search

mysql

first we will create a database with table with name `google_search` and fields like `title`,`link` & `description`

CREATE TABLE IF NOT EXISTS `google_search` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `link` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

And we insert some dummy data into the table

INSERT INTO `google_search` (`id`, `title`, `description`, `link`) VALUES
(1, 'facebook like hashtag system with Php, Mysql & jQuery', 'Now a days hashtag is the fundamental part of a social networking site. Hashtag was first started by twitter but latter followed by every social network like tumblr, facebook, instagram etc. hashtag let you know how much people are talking about that particular topic in the world. Hashtag look like this #hashtag if you dont know what is hashtag you probably havent used a social network.', 'http://hunklessons.blogspot.in/2014/03/facebook-like-hashtag-system-with-php.html'),
(2, 'Select And Upload Multiple Images With jQuery & Ajax', 'HII Guyz my name is Husain Saify Welcome To hunklessons. In this lessons i am going to teach you guyz how to upload images without refreshing the page. For this we are using jQuery and jQuery form plugin it has a Just few lines of JavaScript code, Using this you can upload files, image and videos without refreshing the page.', 'http://hunklessons.blogspot.in/2014/02/select-and-upload-multiple-images-with.html'),
(3, 'Simple DropDown Menu with Keyboard operation shortcut', 'Hi Guyz in this tutorial i am going to teach u how to create a DropDown menu with Keyboard operation shortcut. U can press enter to operate the dropDown menu . Its very easy and basic it have just few lines of code and a beatuful interface', 'http://hunklessons.blogspot.in/2014/04/simple-dropdown-menu-with-keyboard-shortcut.html'),
(4, 'File Upload with Progress bar by Raw AJAX & php', 'Hey Guyz in the tutorial i am going to teach you how to create a file upload system with progress bar with raw ajax. This is very useful for the hosting website because it give a great feedback to the user how much their file has been uploaded. This type to project can be created easily with a code library like jQuery but its greate to create it via raw ajax it give a greate understanding that what is going on', 'http://hunklessons.blogspot.in/2014/04/file-upload-with-progress-bar-by-raw.html'),
(5, 'Css3 Progress Bar', 'Now a days progress bar is a very important in any social media website and progress bar is very easy to create with just a few lines of css and some beautifull css3 transition', 'http://hunklessons.blogspot.in/2014/02/css3-progress-bar.html'),
(6, 'Embed Youtube Videos With JavaScript', 'Guyz i got a request from a reader to make a post for dynamic youtube video embed script so its here. Embed youtube videos is very easy the main thing is a key(id) which i will be explaining up next.', 'http://hunklessons.blogspot.in/2014/02/embed-youtube-videos-with.html'),
(7, 'Drag and Drop Game With html5 & javascript', 'In this post i am going to teach how to create a Drag & Drop Game with Html5 and javaScript. It is very easy and Quite Interesting to create so i stop talking get started', 'http://hunklessons.blogspot.in/2014/02/drag-and-drop-game-with-html5-javascript.html'),
(8, 'Drag & Drop Multiple File Upload Like Facebook', 'In this post me your Dost and Host Husain Saify(hunk husain) is going to teach you to to create a facebook like Drag and Drop Multiple file upload with jQuery & php. For this we are using a uploadFile plugin  Developed by Ravishanker Kusuma Thanx Sir For Developing it.', 'http://hunklessons.blogspot.in/2014/03/drag-n-drop-file-upload-like-facebook.html'),
(9, 'hunkScrollTop.js a jQuery plugin by Husain Saify', 'hey guyz in this post i am going to give you a  hunkScrollTop.js jQuery plugin created by Husain Saify (hunk). Its a light weight plugin with make a dynamic ScrollTop button for your website.', 'http://hunklessons.blogspot.in/2014/03/hunkscrolltopjs-jquery-plugin-by-husain.html'),
(10, 'hunkPlayer.js a jQuery video plugin Created by husain saify', 'hunkPlayer.js is a light weight jQuery plugin which provide a developed by Husain saify. hunkPlayer provide a custom video controls at a html5 video element across browser. hunkPlayer is developed because every browser is developing its own video player and this thing harm the webdeveloper because they want their website to be uniform accross browser and this is possible by hunkPlayer', 'http://hunklessons.blogspot.in/2014/02/hunkPlayer.html');

HTML

html is super easy we have a form with a input field and a submit button and a result div to feed the result fetch from a search.php file

<div class="top-container">
  <img class="logo" src="https://ssl.gstatic.com/accounts/ui/logo_2x.png">
  <form action="search.php" method="GET" id="form">
   <input type="search" id="search" class="search">
   <input type="submit" id="go" class="submit" name="search">
  </form>
  <a href="http://hunklessons.blogspot.com/2014/05/google-like-instant-search-with-ajax.html" target="_blank"><button style="float: right;margin-top: -45px;width: 200px;font-weight: bold;font-size: 20px;">Tutorial & download Script</button></a>
 </div>
 <div id="result-div">
  <center>
   Try keywords like facebook, ajax, a, like, search, hastage
  </center>
 </div>

Css

body{
 margin: 0px;
 padding: 0px;
}
.top-container{
 background: #f1f1f1;
 border: 1px solid #ccc;
 padding: 5px;
 height: 50px;
 position: fixed;
 width: 100%;
}
.logo{
 width: 100px;
 height: 41px;
 padding: 3px 15px;
 float: left;
}
.search{
 height: 30px;
 width: 600px;
 float: left;
 margin-top: 10px;
 border: 1px solid #ccc;
 line-height: 20px;
 padding: 3px;
 font-size: 18px;
}
.submit{
 margin-top: 10px;
 height: 30px;
 width: 30px;
}
#go{
 background: #4285f4;
 border: 0px;
 border-radius: 0px 3px 3px 0px;
 cursor: pointer;
 width: 60px;
 color: white;
}
#result-div{
 min-height: 600px;
 max-height: 100%;
 width: 800px;
 border: 1px solid #ccc;
 border-top: 0;
 margin: 0 auto;
 padding-top: 60px;
}
/*Style for results*/
.result{
 padding: 5px 10px;
 border-bottom: 1px solid #ccc;
}
.result a{
 font-family: verdana;
 font-weight: bold;
}
.result p{
 font-family: verdana;
 font-size: 15px;
}

Javascript

in javascript we are sending the value of the search bar to the search.php page via ajax XMLHttpRequest(); object and then receving the result and json format and displaying the search in the result div

<script type="text/javascript">
	var input = document.getElementById('search'),
		form = document.getElementById('form'),
		resultDiv = document.getElementById('result-div'),
		result = '',
		resultMarkup = '';

	form.addEventListener('submit', function(e){
		//prevent form from submition
		e.preventDefault();
		
		var search = input.value;
		if(search.length > 0){
			resultDiv.innerHTML = '<center><h2>Loading......</h2></center>';
			//creating a ajax request
			var xhr = new XMLHttpRequest();
			xhr.open("GET" ,"search.php?s="+search+"");
			xhr.addEventListener('readystatechange', function(){
				if(xhr.readyState === 4){
					if(xhr.status === 200){
						result = JSON.parse(xhr.response);
						//format the result and display them
						if(result.length){
							for (var i = 0; i < result.length; i++) {
								var title = result&#91;i&#93;.title;
								var desc = result&#91;i&#93;.desc;
								var link = result&#91;i&#93;.link
								resultMarkup += "<div class='result'><a href='"+link+"' target='_blank'>"+title+"</a><p>"+desc+"</p></div>";
							};

							//append the results to the results div
							resultDiv.innerHTML = resultMarkup;
							//empty the resultMarkup variable
							resultMarkup = '';
						}else{
							resultDiv.innerHTML = 'No Result Found';
						}
					}
				}

			}, false);
			xhr.send();
		}else{
			resultDiv.innerHTML = '<center><h2>Enter search term.</h2></center>';
		}
	}, false);
	</script>

index.html – Putting it all together

<html>
<head>
	<title>Google Like Instant Search</title>
	<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
	<div class="top-container">
		<img class="logo" src="https://ssl.gstatic.com/accounts/ui/logo_2x.png">
		<form action="search.php" method="GET" id="form">
			<input type="search" id="search" class="search">
			<input type="submit" id="go" class="submit" name="search">
		</form>
		<a href="http://hunklessons.blogspot.com/2014/05/google-like-instant-search-with-ajax.html" target="_blank"><button style="float: right;margin-top: -45px;width: 200px;font-weight: bold;font-size: 20px;">Tutorial & download Script</button></a>
	</div>
	<div id="result-div">
		<center>
			Try keywords like facebook, ajax, a, like, search, hastage
		</center>
	</div>
	<script type="text/javascript">
	var input = document.getElementById('search'),
		form = document.getElementById('form'),
		resultDiv = document.getElementById('result-div'),
		result = '',
		resultMarkup = '';

	form.addEventListener('submit', function(e){
		//prevent form from submition
		e.preventDefault();
		
		var search = input.value;
		if(search.length > 0){
			resultDiv.innerHTML = '<center><h2>Loading......</h2></center>';
			//creating a ajax request
			var xhr = new XMLHttpRequest();
			xhr.open("GET" ,"search.php?s="+search+"");
			xhr.addEventListener('readystatechange', function(){
				if(xhr.readyState === 4){
					if(xhr.status === 200){
						result = JSON.parse(xhr.response);
						//format the result and display them
						if(result.length){
							for (var i = 0; i < result.length; i++) {
								var title = result&#91;i&#93;.title;
								var desc = result&#91;i&#93;.desc;
								var link = result&#91;i&#93;.link
								resultMarkup += "<div class='result'><a href='"+link+"' target='_blank'>"+title+"</a><p>"+desc+"</p></div>";
							};

							//append the results to the results div
							resultDiv.innerHTML = resultMarkup;
							//empty the resultMarkup variable
							resultMarkup = '';
						}else{
							resultDiv.innerHTML = 'No Result Found';
						}
					}
				}

			}, false);
			xhr.send();
		}else{
			resultDiv.innerHTML = '<center><h2>Enter search term.</h2></center>';
		}
	}, false);
	</script>
</body>
</html>

search.php

In this page we are searching our database for the search term which we have got from the js file and outputting the results in json format

<?php
 //connect to the db
 $confiq = array(
  'host' => 'localhost',
  'username' => 'root',
  'password' => '',
  'dbname' => 'hunklessons',
 );

 $db = new PDO('mysql:host='.$confiq['host'].';dbname='.$confiq['dbname'],$confiq['username'],$confiq['password'].'');
?>

<?php
 if(isset($_GET&#91;'s'&#93;) && !empty($_GET&#91;'s'&#93;)){
  //secure the search input
  $search = trim(strip_tags($_GET&#91;'s'&#93;));

  //convert the space in the search to sepreate terms
  $search_terms = explode(" ", $search);
  $term_count = 0;
  $q = "";
  $result = array();
  $i = 0;

  foreach ($search_terms as $term) {
   $term_count++;
   if($term_count === 1){
    $q .= "`title` LIKE '%$term%' "; 
   }else{
    $q .= "AND `title` LIKE '%$term%' ";
   }
  }

  //prepare the mysql query in PDO
  $query = $db->query("SELECT * FROM `google_search` WHERE $q");

  //get the number of the results found
  $num = $query->rowCount();

  if($num > 0){
   //fetch the result
   while($row = $query->fetch(PDO::FETCH_ASSOC)){
    //put the results in the array
     $result[$i] =  array(
      'title' => $row['title'],
      'desc' => $row['description'],
      'link' => $row['link']
     );
     $i++;
   }
  }

  //convert result array into json format
  $json_result = json_encode($result);
  echo $json_result;
 }
?>

Leave a Reply

Your email address will not be published. Required fields are marked *