JavaScript Tutorial

PHP & Ajax

INTRODUCTION : AJAX stands for Asynchronous Javascript and XML. AJAX is used to make web pages more fast, interactive and dynamic. AJAX helps to update some parts of the page without reloading the whole page. Conventional technique uses synchronous methods to transfer information from and to the server. AJAX uses:

  • XMLHttpRequest object : for exchanging data asynchronously.
  • JavaScript/DOM: for displaying data or to interact with information.
  • CSS: to style the data. 
  • XML : format for transferring the data.

AJAX WITH PHP : We are using an example displaying States according to selected Country using AJAX along with PHP in order to demonstrate how a web server communicates with a web page.

STEP - I: Create MySQL tables 'countries' and 'states' with the following queries.

CREATE TABLE 'countries' (
                           'id' int(11) AUTO_INCREMENT,
                           'name' varchar(50) NOT NULL,
                            PRIMARY KEY  ('id')
                       );
CREATE TABLE 'states' (
                           'id' int(11) AUTO_INCREMENT,
                           'name' varchar(50) NOT NULL,
                           'country_id' varchar(50) NOT NULL,
                            PRIMARY KEY  ('id')
                       );

STEP - II: Insert values into tables accordingly. For example: 

INSERT INTO `countries` (name) VALUES ('AUSTRALIA');
INSERT INTO `countries` (name) VALUES ('INDIA');
INSERT INTO `countries` (name) VALUES ('USA');
INSERT INTO `states`  (name, country_id) VALUES ('New South Wales', 1);
INSERT INTO `states` (name, country_id) VALUES ('Queensland', 1);
INSERT INTO `states` (name, country_id) VALUES ('Victoria', 1);
INSERT INTO `states` (name, country_id) VALUES ('Andhra Pradesh', 2);
INSERT INTO `states` (name, country_id) VALUES ('Gujarat', 2);
INSERT INTO `states` (name, country_id) VALUES ('Punjab', 2);
INSERT INTO `states` (name, country_id) VALUES ('California', 3);
INSERT INTO `states` (name, country_id) VALUES ('Florida', 3);
INSERT INTO `states` (name, country_id) VALUES ('Hawaii', 3);

 

STEP - III: Considering the filename as “ajax_file.php”. HTML Page code will be as follows:

<?php
       $server = "localhost";
       $username = "root";
       $password = "";

        // Creating connection
       $conn = mysqli_connect($server, $username, $password, "mydb");

       if (!$conn) {
    	die(mysqli_connect_error());
       }
       $countriesHTML = "";
       $sql = "SELECT * FROM countries";
       $result = mysqli_query($conn, $sql);
       if (mysqli_num_rows($result) > 0) {
                 while($row = mysqli_fetch_assoc($result)) {
                        $countriesHTML .= "<option value = '".$row['id']."'>".$row['name']."</option>";
                 }
       }else{
              $countriesHTML = "No record found";
       }
?>
<!DOCTYPE html>
<html>
       <head>
                <title>AJAX IMPLEMENTATION</title>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
       </head>
       <body>
               <table>
                         <tr>
                               <td>Country : </td>
                                <td>
                                      <select id="country" name="country">
                                              <?php echo $countriesHTML; ?>
                                      </select>
                                </td>
                         </tr>
                          <tr>
                                <td>States : </td>
                                <td>
                                      <select id="states" name="states">

                                      </select>
                                </td>
                         </tr>
               </table>
              <script>
   		 $(document).ready(function() {
   			 $( "#country" ).change(function() {
   			 	var countryID = $("#country").val();
   			 	$.ajax({
   					type : "POST",
   				 	dataType: "json",
   				 	url : "ajax_process.php",
   					cache: false,
   				 	data : { countryID : countryID},
   				 	success: function (data) {  
   						 var res = data;
   						 var html = '';
   						 for(var i = 0; i < res.length; i++){
   					                   html += "<option value='"+res[i]['id']+"'>"+res[i]['name']+"</option>";
   						 }
   						 $("#states").html(html);
   				 	}
   				 });
   			 });
   		 });        	 
    	</script>
       </body>
</html>

 

ajax_process.php

<?php
	$server = "localhost";
	$username = "root";
	$password = "";

  	// Creating connection
	$conn = mysqli_connect($server, $username, $password, "mydb");

	if (!$conn) {
    	      die(mysqli_connect_error());
	}
           $statesArr = array();
            $sql = "SELECT * FROM states WHERE country_id = '".$_POST['countryID']."'";
	$exe = mysqli_query($conn, $sql) or die("SQL Error");
	if (mysqli_num_rows($exe) > 0) {
    	       while($row = mysqli_fetch_assoc($exe)) {
   		 $arr['id'] = $row['id'];
        	             $arr['name'] = $row['name'];
   		 $statesArr[] = $arr;
    	      }
	}else{
    	     $statesArr = array();
	}
           die(json_encode($statesArr));
?>

 

 

Go back to Previous Course