jQuery UI Autocomplete For Two Fields Using PHP Ajax and MySQL
This jQuery UI Autocomplete For Two Fields Using PHP Ajax and MySQL fills the Client Address if users selects the jQuery UI autocomplete results. This is request tutorial that I implemented in my smart invoice system. Please check that if you type ‘L’ in client name textbox, it will show autocomplete suggestion. Then if User select’s the result it will automatically fills the address of the client.
Please refer my previous jQuery autocomplete tutorials
This jQuery Autocomplete Working Description:
When user types text in textbox, it will automatically auto suggest the list of all client names using jQuery UI autocomplete. Then when user selects the one of the client name, then in select event of jQuery UI autocomplete I get client ID, using that I make Ajax request to get that client company address to fill the address text-area.
Create index.html file and add basic HTML markup in it.
Create a directory called auto in your htdocs or in your server root folder. Now add create following list of folders (css, js ) in the auto directory. Then download bootstrap and jQuery files and add in their respective css and js directories. Now create index.html file and include those css and js files in index.html file.
<!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 ui autocomplete</title> <!-- Bootstrap --> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,200' rel='stylesheet' type='text/css'> <link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <link href="css/style.css" rel="stylesheet"> <!-- Script --> <script src="js/jquery.min.js"></script> </head> <body> <!-- Begin page content --> <div class="container content-invoice"> </div> <script src="js/jquery-ui.min.js"></script> <script src="js/bootstrap.min.js"></script> <div class="clearfix"></div> <footer class="footer"> <div class="container-fluid"> <p class="text-center">© Copyright by <a href="http://smarttutorials.net/" target="_blank">Smart Tutorials</a> <?php echo CURRENT_YEAR; ?></p> </div> </footer> </body> </html>
You may also interested in Learning jQuery Autocomplete from scratch. Checkout Video Tutorials series on: jQuery UI Autocomplete from Scratch
Learn jQuery Autocomplete in 3 Minutes
Create HTML FORM with Required Fields For jQuery UI Autocomplete:
Create simple HTML Form with textbox and text area in it. Here is my HTML markup for this tutorial.
<div class="container content-invoice"> <h1 class="text-center title">jQuery UI Autocomplete 2 Fields</h1> <h1> </h1> <form method="post"> <div class="row"> <div class="col-xs-12 col-sm-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-3 col-md-3 col-lg-3 "> <div class="form-group"> <input type="text" placeholder="Company Name" id="clientCompanyName" name="data[clientCompanyName]" class="form-control ui-autocomplete-input" value="" autocomplete="off"> </div> </div> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 text-center"> <button type="button" id="myButton" class="btn btn-success" autocomplete="off" style="display: none"> Loading.... </button> </div> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 "> <div class="form-group"> <textarea placeholder="Your Address" id="clientAddress" name="data[clientAddress]" rows="3" class="form-control txt"></textarea> </div> </div> </div> </form> </div>
Add jQuery UI Autocomplete to Textbox:
Now I am going to add jQuery UI Autocomplete to textbox. So when user searches/enter the Client company name, then this jQuery UI Autocomplete will show auto suggestion based available list client names in the database.
<script> $('#clientCompanyName').autocomplete({ source: function( request, response ) { $.ajax({ url : 'ajax.php', dataType: "json", method: 'post', data: { name_startsWith: request.term, type: 'customerName' }, success: function( data ) { response( $.map( data, function( item ) { var code = item.split("|"); return { label: code[1], value: code[1], data : item } })); } }); }, autoFocus: true, minLength: 1, select: function( event, ui ) { $('#myButton').show(); var names = ui.item.data.split("|"); $(this).val(names[1]); getClientAddress(names[0]); } }); </script>
This above script will make ajax request to server (i.e. ajax.php ) whenever user types something in the textbox with id of clientCompanyName. Where ajax.php gets the user entered text and queries the database. Finally sends the result in json format.
Select Event Of jQuery UI Autocomplete:
When user selects the particular client name from the list of available Clients in auto suggestion, then jQuery UI Autocomplete select event is fired where I am getting selected client ID.
<script> select: function( event, ui ) { $('#myButton').show(); var names = ui.item.data.split("|"); $(this).val(names[1]); getClientAddress(names[0]); } </script>
Now I am passing that client Id to getClientAddress() function to make Ajax request, that gets the selected Client address from the database.
<script> function getClientAddress(id){ $.ajax({ url: "ajax.php", method: 'post', data:{id:id, type:'clientAddress'}, success: function(result){ $('#myButton').html('Completed'); setTimeout(function(){ $('#myButton').html('Loading....').slideUp("slow"); }, 1000); $("#clientAddress").html(result); } }); } </script>
Crate config.php File To keep Database Connections and Site wide Constants:
I am creating config.php file to keep database connections and site wide constants. Here is my config.php file.
<?php /* Site : http:www.smarttutorials.net Author :muni */ //site specific configuration declartion define( 'BASE_PATH', 'http://localhost/invoice/'); define('DB_HOST', 'localhost'); define('DB_NAME', 'smart_invoice'); define('DB_USERNAME','root'); define('DB_PASSWORD',''); $con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); define( 'CURRENT_YEAR', date("Y"));
Crate ajax.php File To Handle jQuery UI autocomplete Ajax Request:
Finally create ajax.php to handle jQuery UI autocomplete Ajax Request when user types client name in textbox. Here is my ajax.php file PHP script.
<?php /* Site : http:www.smarttutorials.net Author :muni */ require_once 'config.php'; if(isset($_POST['type']) && $_POST['type'] == 'customerName' ){ $type = $_POST['type']; $name = $_POST['name_startsWith']; $query = "SELECT id, customerName FROM customers where UPPER($type) LIKE '%".strtoupper($name)."%'"; $result = mysqli_query($con, $query); $data = array(); while ($row = mysqli_fetch_assoc($result)) { $name = $row['id'].'|'.$row['customerName']; array_push($data, $name); } mysqli_close($con); echo json_encode($data);exit; } if(isset($_POST['type']) && $_POST['type'] == 'clientAddress' ){ $id = $_POST['id']; $query = "SELECT id, addressLine1, addressLine2, city, state, country, phone FROM customers WHERE id =$id"; $result = mysqli_query($con, $query); $data = mysqli_fetch_assoc($result); $address = ''; if(!empty( $data )){ $address = isset($data['addressLine1'])? $data['addressLine1'].', ' : ''; $address .= isset($data['addressLine2'])? $data['addressLine2'].', ': ''; $city = isset($data['city'])? $data['city']: ''; $state = isset($data['state'])? $data['state']: ''; $country = isset($data['country'])? $data['country']: ''; $phone = isset($data['phone'])? $data['phone']: ''; $address .=$city.','.$state.', '; $address .=$country.', '; $address .=$phone.'.'; } mysqli_close($con); echo $address;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] muni2explore[at]gmail.com
Note: But it will be charged based on your customization requirement