How to use IP2Location geolocation data with jQuery UI autocomplete plugin

In this tutorial, we will show you how to integrate IP2Location geolocation data with the autocomplete plugin from jQuery UI. Here is what we are going to demonstrate; to automatically get the country information based on the visitor’s IP address, then allowing user to select the region and city name by using the autocomplete textbox from jQuery UI.

First and foremost, you need to create a new database. In this tutorial, we will use the IP2Location™ LITE IP-COUNTRY-REGION-CITY Database. This database can be downloaded from https://lite.ip2location.com/database/ip-country-region-city for free. Below are the steps to create the geolocation database.

Step 1 Create the ‘ip2location_db3lite’ table

CREATE TABLE `ip2location_db3lite` (
`ip_from` INT(10) NOT NULL,
`ip_to` INT(10) NOT NULL,
`country_code` CHAR(2) NOT NULL,
`country_name` VARCHAR(64) NOT NULL,
`region_name` VARCHAR(128) NOT NULL,
`city_name` VARCHAR(128) NOT NULL,
INDEX `idx_ip_from` (`ip_from`),
INDEX `idx_ip_from_to` (`ip_from`, `ip_to`),
INDEX `idx_ip_to` (`ip_to`),
INDEX `idx_cc_rn` (`country_code`, `region_name`),
INDEX `idx_cc_rn_cn` (`country_code`, `region_name`, `city_name`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

Step 2 Import the geolocation data file into the table

LOAD DATA LOCAL
INFILE 'IP2LOCATION-LITE-DB3.CSV'
INTO TABLE
`ip2location_db3lite`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 0 LINES;

Step 3: Write the backend logic

In this step we will show how to implement the autocomplete plugin from jQuery UI with the IP2Location LITE database. First, we need to include 2 javascript files into the project. Please see the below.


<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Below are the HTML code:


<label>Country Name: </label>
<label><?php print $country_name; ?></label>
<br /><br />
<div class="ui-widget">
<form action="" method="post">
<label for="region">Region Name: </label>
<input type="text" id="region">
<br /><br />
<label for="city">City Name: </label>
<input type="text" id="city" oninput="myFunction()">
<br /><br />
<input class="ui-button" type="submit" value="submit">
</form>
</div>

On the initial page load, retrieve the country name based on the visitor’s IP address for display. For the input text field, the oninput, it will trigger myFunction() to retrieve the location information based on user input.

In next step we will show you how to add the data source for both text fields. For that, we will be using search1.php. What search1.php does is to fetch a complete list of region name from database based on the displayed country name into the array for processing. So first please include search1.php before the html tag like this: <?php include 'search1.php';?>. Below are the codes for the implementation:


$( "#region" ).autocomplete({
source: <?php echo json_encode($regionname);?>
});

<script type="text/javascript">
function myFunction() {
var x = document.getElementById("region").value;
if (x == '') {
alert("Please Enter the Anything");
} else {
$.ajax({
method: "POST",
url: "search1.php",
data: {region_name:x},
dataType:"json",
success: function(data) {
$( "#city" ).autocomplete({
source: data
});
}
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
}
</script>

The function above (myFunction) will take the region name entered by user to retrieve the city names in search1.php using AJAX. In the next step, we will show you how to create the search1.php file.

Step 4: Create search1.php

<?php

//connect to database
$connect = mysqli_connect("localhost", "root", "", "ip2location");

//retrieve countryName based on ipaddress

//Get the visitor IP address
//$ip = $_SERVER['REMOTE_ADDR'];
//In case you are testing locally with 127.0.0.1,
//you can uncomment the below line to assign the IP address
//to 8.8.8.8 (or whatever) for your testing.
$ip= "8.8.8.8";

// Function to convert IP address (xxx.xxx.xxx.xxx) to IP number (0 to 256^4-1)
function Dot2LongIP ($ip) {
if ($ip == ""){
return 0;
}else {
$ips = explode(".", $ip);
return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
}
}

// Convert IP address to IP number for querying database
$ipno = Dot2LongIP($ip);

//start to query from database
$query = 'select DISTINCT country_name,country_code from ip2location_db3lite where "'.$ipno.'"<= ip_to AND ip_from<="'.$ipno.'"';
$result = mysqli_query($connect, $query);

//check if query is successful
if(!empty($result)){
while($row = mysqli_fetch_assoc($result)){
//save the result into local variable for future usage
$country_name = $row["country_name"];
$country_code = $row["country_code"];
}
}

//do the query to fetch the region_name and city_name
//if the region name is empty, a list of region name will be fetched and sent back to the page
//if the region name is set, a list of city name will be fetched based on the user selected region name and sent back to the page
if(empty($_POST["region_name"])){
$sql = "select DISTINCT region_name from ip2location_db3lite where country_code = '".$country_code."' GROUP BY region_name";
$result = mysqli_query($connect, $sql);
$regionname = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$regionname[] = $row["region_name"];
}
}
}else{
$region_name = mysqli_real_escape_string($connect, $_POST["region_name"]);
$sql = "select DISTINCT city_name from ip2location_db3lite where country_code = '".$country_code."' AND region_name = '".$region_name."' GROUP BY city_name";
$result = mysqli_query($connect, $sql);
$cityname = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$cityname[] = $row["city_name"];
}
}
echo json_encode($cityname);
}

?>

The search1.php does 3 things:

  1. Get the country name based on the visitor’s IP address
  2. Fetch a list of region names based on the visitor’s IP address
  3. Fetch a list of city names based on the visitor’s IP address

Below is the example of the screenshot for the above tutorial:

Below is the complete code:

<?php include 'search1.php';?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="../../themes/base/all.css">
<link rel="stylesheet" href="../demos.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<label>Country Name: </label>
<label><?php print $country_name; ?></label>
<br /><br />
<div class="ui-widget">
<form action="" method="post">
<label for="region">Region Name: </label>
<input type="text" id="region">
<br /><br />
<label for="city">City Name: </label>
<input type="text" id="city" oninput="myFunction()">
<br /><br />
<input class="ui-button" type="submit" value="submit">
</form>
</div>
<br /><br />
<div class="demo-description">
<p>The Autocomplete widgets provide suggestions while you type into the field.</p>
<p>Here the country name is determined by the user's ip address and the region name and city name provided as suggestions</p>
</div>
</body>
<script type="text/javascript">
$( "#region" ).autocomplete({
source: <?php echo json_encode($regionname);?>
});
function myFunction() {
var x = document.getElementById("region").value;
if (x == '') {
alert("Please Enter the Anything");
} else {
$.ajax({
method: "POST",
url: "search1.php",
data: {region_name:x},
dataType:"json",
success: function(data) {
$( "#city" ).autocomplete({
source: data
});
}
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
}

</script>
</html>

Was this article helpful?

Related Articles