Step 4 – Writing script to get data from MySQL database
<?php
$pincode = $_GET['pincode'];
$conn = mysql_connect("localhost", "root", "password");
mysql_select_db("turnouts") or die();
$pincode = (string)mysql_real_escape_string($pincode);
$sql = "SELECT taluka, district, state FROM pincode WHERE pincode = '$pincode'";
$data = mysql_query($sql);
if(!$data) {
die(mysql_error());
}
$row = mysql_fetch_row($data);
$taluka = $row[0];
$district = $row[1];
$state = $row[2];
$state = str_replace("\r\n", "", $state);
$taluka = strtolower($taluka);
$district = strtolower($district);
$state = strtolower($state);
header('Content-type: application/json');
$array = array('taluka'=>$taluka, 'district'=>$district, 'state'=>$state);
echo json_encode($array);
?>
The URL will follow the pattern, /retrieve.php?pincode=000000 and return data. As an example, the following image,
If you have come successfully to this step, then bingo! We now have a working API.
Step 5 – Writing an AJAX form using jQuery
<html>
<head>
<title>Pincodes</title>
<script src="js/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="form">
<label for="pincode">Pincode:</label>
<input type="text" name="pincode" id="pincode" required /><br />
<label for="taluka">Taluka:</label>
<input type="text" name="taluka" id="taluka" /><br />
<label for="district">District: </label>
<input type="text" name="district" id="district"><br />
<label for="state">State:</label>
<input type="text" name="state" id="state"><br />
</div>
<script>
$(document).ready(function() {
$('#pincode').keyup(function(e) {
var pincode = $(this).val();
if(pincode.length == 6 && $.isNumeric(pincode)) {
var req = 'retrive.php?pincode=' + pincode;
$.getJSON(req, null, function(data) {
$('#taluka').val(data.taluka);
$('#district').val(data.district);
$('#state').val(data.state);
});
};
});
</script>
</body>
</html>
Some explanation goes here.
The .keyup() event fires when a key is pressed in that field. We could have use onFocus() or onBlur() in javascript but that only fires when a field is focused or blurred, so this is much better. Since we have pincodes of length 6 digits here in India, to prevent script from querying for the first five digits, we have added a if(pincode.length == 6) to our code.
As I said, the even fires as soon as one enters the 6th digit and populates the remaining three fields with the data it retrieves.
It is hard to show it in a still image, but having just entered the pin, rest of the fields get populated.