How To Create Dynamic Autocomplete search using Bootstrap Typeahead JS ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you a example of how to add dynamically Autocomplete by using typeahead dynamic. So now in this post i will give you a full example that way we can run this example easily in our project. And after run this example we can see our expected output like as we want.

At first we will create the ajax.html file for on html layout in this file i will added the jquery and Bootstrap Typeahead code. So When we are write on input box then we can find the Dynamic Autocomplete search by using ajax requiest.

So, first need to create aja.html file and then copy the bellow code.

ajax.html
<html lang="en">
<head>
    <title>Bootstrap Typeahead with Ajax Example</title>  
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  
</head>
<body>


<div class="row">
	<div class="col-md-12 text-center">
		<br/>
		<h1>Search Dynamic Autocomplete using Bootstrap Typeahead JS</h1>	
			<input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
	</div>
</div>


<script type="text/javascript">


	$('input.typeahead').typeahead({
	    source:  function (query, process) {
        return $.get('/ajaxpro.php', { query: query }, function (data) {
        		console.log(data);
        		data = $.parseJSON(data);
	            return process(data);
	        });
	    }
	});


</script>
</body>
</html>

Okay, now we have to create the another page for the getting json data by our ajax requiest. So need to create an another page name ajaxpro.php file and then copy bellow code.

ajaxpro.php

<?php
	

	define (DB_USER, "root");
	define (DB_PASSWORD, "root");
	define (DB_DATABASE, "learn");
	define (DB_HOST, "localhost");
	$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);


	$sql = "SELECT items.title FROM items 
			WHERE title LIKE '%".$_GET['query']."%'
			LIMIT 10"; 
	$result = $mysqli->query($sql);
	

	$json = [];
	while($row = $result->fetch_assoc()){
	     $json[] = $row['title'];
	}


	echo json_encode($json);

Read Also: Generate Captcha code and Validation by using BotDetect package in laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →