Please support us by disabling ad blocker for smarttutorials.net ...

Two Fields jQuery UI Autocomplete Using Jquery PHP MYSQL

Posted by & filed under Ajax, HTML5, JAVASCRIPT, JQUERY, MYSQL, PHP.

In this tutorial we are going to see how to show state name and country name in the same text field. Before continuing this tutorial please check my previous tutorials on jQuery autocomplete.

jquery autocomplete integration

jQuery Autocomplete Mutiple Fields Using jQuery, Ajax, PHP and MySQL

jQuery UI Autocomplete For Two Fields Using PHP Ajax and MySQL

Invoice System Using jQuery AutoComplete

jQuery Autocomplete Post Tagging System Like In WordPress

jQuery Autocomplete Search using PHP, MySQL and Ajax

jQuery Autocomplete For Two Fields

jQuery Autocomplete For Two Fields

Two Fields jQuery UI Autocomplete Working Description:

When user types the city or state name in the textbox, It will make ajax request to apache server, where PHP will make connection to MySQL database and get the city and state names based on user entered data in the textbox. Then Apache server return those response, finally jQuery UI autocomplete will show the city and state name as suggestions to select.

 

Create index.php file and add basic HTML markup in it.

Create a directory called auto in your htdocs/root folder. Now add the following list of folders (css, js ) in the auto directory. Then download bootstrap and jQuery, jQuery UI files and add in their respective css and js directories. Now create index.php file and include those css and js files in index.php file. Now add the following basic HMTL markup in it.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>jQuery Autocomplete for Two Fields PHP MySQL</title>
		
		<!-- Bootstrap -->
		<link href="css/jquery-ui.min.css" rel="stylesheet">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link rel="stylesheet" href="css/font-awesome.min.css">
		<link rel="stylesheet" href="css/style.css">
	</head>
<body>
	
	<script src="js/jquery.min.js"></script>
	<script src="js/jquery-ui.min.js"></script>
	<script src="js/bootstrap.min.js"></script>
</body>
</html>

Set Body Background Image Full Screen Using CSS

Now we are going to set Full screen background image using background-size: cover property.

body {
	overflow-x: hidden;
	background: rgba(0, 0, 0, 0) url('../img/bg.jpg') no-repeat fixed center center /cover;
	width: 100%;
	color: white;
}

Create jQuery Autocomplete HTML5 Form & Designing:

Now we are going to design HTML5 Form to search city & state names. Now add the following HTML markup between the body tags.

<div class="container" id="outer_container">
	<div class="table">
		<div class="header-text">
			<div class="row">
				<div class="col-md-12 text-center">
					<form class="form-inline">
						<div class="form-group">
							<div class="input-group">
								<div class="input-group-addon"><i class="fa fa-map-marker"></i> </div>
								<input type="text" class="form-control" id="city" placeholder="Search City & State">
							</div>
						</div>
						<div class="form-group" id="res-form-group">
							<div class="input-group">
								<div class="input-group-addon"><i class="fa fa-search"></i> </div>
								<input type="text" class="form-control" id="exampleInputAmount" placeholder="Search for restaurant, cuisine or a dish">
							</div>
						</div>
						<div class="form-group">
							<button class="btn btn-danger">Search</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>

Here is the CSS style of the design.

#outer_container .table {
	display: table;
	height: 100%;
}

#outer_container.container {
	height: 100%;
}

#outer_container .header-text {
	display: table-cell;
	text-align: center;
	vertical-align: middle;
	color: white;
}


.btn{
	padding: 22px 30px;
}
.input-group-addon{
	border-radius:0px;
	padding: 22px 20px;
}

.form-control {
	font-size: 18px;
	position: relative;
	left: 0;
	height: auto;
	padding: 20px 30px;
	border: 1px;
	border-radius: 0;
	box-shadow: 0;
}

.form-control.form-white {
	color: #fff;
	border: 2px solid white;
	background: transparent;
	-webkit-transition: background-color 0.3s;
	transition: background-color 0.3s;
}

.form-control.form-white::-webkit-input-placeholder {
	/* WebKit browsers */
	color: #fff;
}

.form-control.form-white:-moz-placeholder {
	opacity: 1;
	/* Mozilla Firefox 4 to 18 */
	color: #fff;
}

.form-control.form-white::-moz-placeholder {
	opacity: 1;
	/* Mozilla Firefox 19+ */
	color: #fff;
}

.form-control.form-white:-ms-input-placeholder {
	/* Internet Explorer 10+ */
	color: #fff;
}

.form-control.form-white:focus {
	background: rgba(255,255,255,0.2);
}

Attach jQuery UI Autocomplete Event to Form Element:

Now we are going to select an Form element and attaching the jQuery UI Autocomplete Event to it. Here is the jQuery UI Autocomplete Event script.

$('#city').autocomplete({
	source: function( request, response ) {
		$.ajax({
			url: 'ajax.php',
			dataType: "json",
			method: 'post',
			data: {
				name_startsWith: request.term,
				type: 'city'
			},
			success: function( data ) {
				response( $.map( data, function( item ) {
					console.log(item);
					//var code = item.split("|");
						return {
							label: item,
							value: item,
							data : item
						}
					}));
				}
			});
	},
	autoFocus: true,
	minLength: 1,
	select: function( event, ui ) {
		//on select
	}
});

Create a Sample MySQL Table and Add Sample Data in it:

 

Create a sample MySQL Database and create cities table in it using following SQL queries.

CREATE TABLE IF NOT EXISTS `cities` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `city_name` varchar(100) NOT NULL,
  `city_state` varchar(100) NOT NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

INSERT INTO `cities` (`city_id`, `city_name`, `city_state`) VALUES
(1, 'Kolhapur', 'Maharashtra'),
(2, 'Port Blair', 'Andaman and Nicobar Islands'),
(3, 'Adilabad', 'Andhra Pradesh'),
(4, 'Adoni', 'Andhra Pradesh'),
(5, 'Amadalavalasa', 'Andhra Pradesh'),
(6, 'Amalapuram', 'Andhra Pradesh'),
(7, 'Anakapalle', 'Andhra Pradesh'),
(8, 'Anantapur', 'Andhra Pradesh');

Create config.php File:

Now create config.php file, and add site wide constant and database connection it. This config file help us to keep all config related things in one place. Here is my PHP config file script.

<?php
define( 'BASE_PATH', 'http://localhost/marcelo/');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'sh');


$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

Crate ajax.php File To Handle jQuery UI autocomplete Ajax Request:

Now create ajax.php file that will receive all the ajax request from the client side. Whenever user enter something in the textbox jQuery UI autocomplete event triggered that’s make ajax request with user entered data to the ajax.php file. Now in the ajax.php I will get those data and make a connection to MySQL database to get those filtered data. Finally ajax.php will return those data to client.

<?php
/*
Site : http:www.smarttutorials.net
Author :muni
*/
require_once 'config.php';

if(isset($_POST['type']) && $_POST['type'] == 'city' ){
	$type = $_POST['type'];
	$name = $_POST['name_startsWith'];
	$query = "SELECT city_name, city_state FROM cities where UPPER(city_name) LIKE '".strtoupper($name)."%'";
	$result = mysqli_query($con, $query);
	$data = array();
	while ($row = mysqli_fetch_assoc($result)) {
		$name = $row['city_name'].','.$row['city_state'];
		array_push($data, $name);
	}
	mysqli_close($con);
	echo json_encode($data);exit;
}

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!