Change country flags and ISD code using PHP MySQL Ajax and jQuery

by  
Share:
Change country flags and ISD code using PHP MySQL Ajax and jQuery

In my last tutorial I have shared the list of all countries names with ISO and ISD codes in SQL and CSV format. So I thought, it would be great if I create a tutorial to include country flags as well as change country ISD code based on country selection. In this tutorial you will learn how to change country flags and ISD code using PHP MySQL Ajax and jQuery.

View Demo

Steps to change country flags and ISD codes

Keeping things simple, I would like to tell you what we are going to to. There will a list of countries name with ISD and ISO codes in our database. On the frontend i.e. browser we will fetch the countries list from the database and display it on a select dropdown box. whenever a user selects any country from the dropdown its respective country flag with ISD code will be displayed dynamically. We will be using the AJAX technique i.e only a part of the page will be changed.

Make sure you have created a database and after that create a table “countries“. You can download the total script (at the end of the article) which has the sql file or you can also copy the database which has been already posted in my last article List of all countries name with ISD and ISO code in SQL and CSV format.

Moving forward, If you guys are aware of my tutorial you will know that I use PHP PDO classes for database interaction. So lets just move ahead and create a basic config file where we can set all database constants and create database connection.

config.php

<?php
define('DB_DRIVER', 'mysql');
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", '');
define("DB_DATABASE", "mydb");

// basic options for PDO 
$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

//connect with the server
try {
    $DB = new PDO(DB_DRIVER . ':host=' . DB_HOST . ';dbname=' . DB_DATABASE, DB_USER, DB_PASSWORD, $dboptions);
} catch (Exception $ex) {
    echo($ex->getMessage());
    die;
}
?>

Once the database connection is done. Create a file called index.php which is your landing page of the project. Make a query to the database to fetch the list of the countries and then display it on the dropdown box.

index.php

<?php
$sql = "SELECT `countries_id`, `countries_name`, `countries_iso_code`, `countries_isd_code` "
        . " FROM `countries` WHERE 1 "
        . " ORDER BY countries_name ASC";
try {
    $stmt = $DB->prepare($sql);
    $stmt->execute();
    $results = $stmt->fetchAll();
} catch (Exception $ex) {
    echo($ex->getMessage());
}
?>

Display the countries results in a dropdown box. Also bind it with onchange event so whenever the user selects any country it will change the country flag and ISD code by firing an Ajax request using Jquery.
<select name="country" id="country" onchange="displayRecords(this.value);">
  <option value="">Select</option>
  <?php foreach ($results as $rs) { ?>
  <option value="<?php echo trim($rs["countries_iso_code"]); ?>"><?php echo trim($rs["countries_name"]); ?></option>
  <?php } ?>
</select>

Set your flag container and ISD code textfield area with unique ID attribute where the result is to be displayed. I am also showing the name of the selected country as well. It is optional you can leave it if you don’t want to.
<!-- flag placeholder with ID name as cflag -->
<img id="cflag" src="" alt=""/>

<!-- ISD CODE placeholder with ID name as isd_code-->
<input type="text" id="isd_code" placeholder="ISD CODE" name="isd_code" value="" readonly="">

<!-- country name placeholder with ID name as cname -->
<div id="cname"></div>

Create a custom JavaScript function displayRecords() that will fire an Ajax request to another PHP file which will return the results as a JSON string. On success this function will then parse the Json string and display the values on their respective placeholders that are marked by ID. If you are new to jquery ajax and json read these tutorials  How to parse json with jquery and ajax and Read and write json file with php and mysql.
function displayRecords(country_iso_code) {
	var country_iso_code = $.trim(country_iso_code);
	if (country_iso_code.length > 0) {
		$.ajax({
			type: "GET",
			url: "getvalue.php",
			data: "isocode=" + country_iso_code,
			cache: false,
			beforeSend: function() {
				$('.loader').html('<img src="loader.gif" alt="" width="24" height="24"" >');
			},
			success: function(html) {
				$("#results").html(html);
				// parsing the json results
				var parsedData = jQuery.parseJSON(html);
				// resetting the values
				$('#isd_code').val('');
				$('#cflag').attr("src", "");
				$('#cname').html('');
				// checking if there are results or not
				if (Object.keys(parsedData).length > 0) {
					$('#isd_code').val($.trim(parsedData.c_isd));
					$('#cflag').attr("src", "flags/"+$.trim(parsedData.c_iso)+".png");
					$('#cname').html($.trim(parsedData.c_name));
				}
				$('.loader').html('');
				
			}
		});
	} else {
		// setting the default values
		$('#isd_code').val('');
		$('#cflag').attr("src", "");
		$('#cname').html('');
	}
}

Once you are done with the index page, all you need to do is to create the a php page called getvalue.php that will return the results in json format based on the user selected country.

getvalue.php

<?php
require_once("config.php");
$isd_code = (trim($_GET["isocode"]) <> "" ) ? trim($_GET["isocode"]) : "";
$arr = array();

$sql = "SELECT `countries_id`, `countries_name`, `countries_iso_code`, `countries_isd_code` "
        . " FROM `countries` WHERE 1 AND countries_iso_code LIKE :iso  ORDER BY countries_name ASC";
try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":iso", $isd_code);
    $stmt->execute();
    $results = $stmt->fetchAll();
    
} catch (Exception $ex) {
    echo($ex->getMessage());
}
if (count($results) > 0 ) {
    $arr = array(
        "c_id" => $results[0]["countries_id"],
        "c_name" => $results[0]["countries_name"],
        "c_iso" => strtolower($results[0]["countries_iso_code"]),
        "c_isd" => $results[0]["countries_isd_code"],
    );
}
echo json_encode($arr);
exit;
?>

I think this is the most easiest Jquery Ajax Json parsing tutorial you will come across. Using this technique you can create some advance script like creating multiple dropdown  based on user selection. You can have a look at this tutorial Multiple dropdown with jquery ajax and php.

View Demo
Download

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Niraj on

Great Job…

Reply
Shahrukh Khan on

thanks

Reply
Talentelgia on

I just went through your blogs. You are really doing a great thing by writing technically in a very informative manner. Keep doing!

Reply
Shahrukh Khan on

Thanks for your appreciation.

Reply
carhire on

It’s going to be finish of mine day, however before end
I am reading this impressive post to improve my knowledge.

Reply
jai on

Good article….

Reply
Julien on

Nice tutorial, i was looking for that and it well explained!

Reply
Tyag Raj on

Hey Shahrukh, this is an excellent and very detailed post on changing country flags and ISD code with the help of PHP MySQL Ajax and jQuery. I really appreciate the way you have given the code snippet and made everything very clear.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.