PHP (Core & Framework)

How to create Auto Filled textbox using AJAX in php from MYSQL

auto-fill-text-box

To view the live demo please open url https://jobplatform.in/job_search.php and type kol or starting 3 letters of any city name in the location textbox.

If you want to fill a text box content automatically from the mysql database table using AJAX then use the following code:

Setp 1 – Create a table named “location” with 2 columns – loc_id and city in your mysql database

Input some citi names in this table

Setp 2 – Create one PHP page and add the following code

 

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”<html>
<head>
<title>Job Platform – Software Jobs, Hardware Jobs, Engineering Jobs, Freshers Jobs</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>

<!– jQuery library –>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
<!– jQuery UI library –>
<link rel=”stylesheet” href=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js”></script>

</head>

<body leftmargin=”0″ topmargin=”0″ marginwidth=”0″ marginheight=”0″>

<form name=”f1″ method=”post” action=”job_results.php”

<input type=”text” name=”mycity” id=”mycity”> just input first 3 letters of city
<input type=”hidden” name=”loc_id” id=”loc_id”>

</form>

<script>

$(function() {

$(‘#mycity’).attr(‘autocomplete’, ‘off’);
$(“#mycity”).autocomplete({
minLength: 3,
source: “get_city.php”,
select: function( event, ui ) {
event.preventDefault();
$(“#mycity”).val(ui.item.value);
$(“#loc_id”).val(ui.item.id);
}
});
});
</script>
</body>
</html>

Setp 3 – Create another PHP page get_city.php and add the following code into that PHP page.

<?php
include(‘connect.php’);  //put your connection code in this file
$searchTerm = $_GET[‘term’];
$sql=”select loc_id, city from location where city like ‘$searchTerm%'”;
$rsCity=mysql_query($sql);

$cityData = array();
if(mysql_num_rows($rsCity) > 0)
{
while($row = mysql_fetch_assoc($rsCity))
{
$data[‘id’] = $row[‘loc_id’];
$data[‘value’] = $row[‘city’];
array_push($cityData, $data);
}
}

// Return results as json encoded array
echo json_encode($cityData);

?>

 

Comment here