- SPLessons

Ajax call using JQuery and PHP

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Ajax call using JQuery and PHP

 Ajax call using JQuery and PHP 


 

Now in these days Ajax is a powerful tool to change particular content of web page without refreshing page.The following simple Ajax call shows the relation between two dropdowns(parent and child).

Description :

I have two dropdowns one is County(parent) and State(children). In these country is static having values (India, US, UK, Australia, Germany). Once I selected the dropdown as India then according to that States which are in India needs two fill in State dropdown. The following steps will help to achieve this.

 

Step1 :

Add the below tables in your database.
1. Country
2. State

Step2 :

Create a PHP file and give the name ‘db.php’ and add below code in that file.


<?php 

    // These variables define the connection information for your MySQL database
    $username = "root";
    $password = "";
    $host = "localhost";
    $dbname = "ajax_demo";  // your database name 

    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
    try
    {
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
    }
    catch(PDOException $ex)
    { 

        die("Failed to connect to the database: " . $ex->getMessage());
    }
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

   ?>

Step3 :

Add below code in javascript


      <script type="text/javascript" >
         $(function () {
         $("#country").change( function () {

         if($(this).val()=="0")
         {
          alert("Please select country");
          return false;
         }
         else {
         var country=$(this).val();

          data="country="+country;
         	$.ajax({
         	  type: "POST",
         	  url: "ajax_State.php",
         	  data: data,
         	  success: function (response) {
         		  $("#state").html(response);
         		}

         	});
         }
         });

         });

      </script>

Step4 :

Add below code in HTML body 

<?php  include 'db.php'; ?>

 

<select id='country'>
 <option value="0">Select Country</option>

 

    <?php

    $query1="select * from country";
			$stmt = $db->prepare($query1);
			$stmt->execute();
			if ($stmt->rowCount()) {
                           while ($row = $stmt->fetch()) {
		          echo "<option value='".$row['id']."' >".$row['Country_name']."</option>";
	 } } ?>     

 

 </select>

<br />  <br />  	                       

  <select id='state'>
    <option value="0">Select State</option>

  </select>

Step5 :

Add below code in ‘ajax_State.php’ page

<?php include "db.php";
  echo "<option value='0'>Select State</option>";
    $Country=$_POST["country"];
      $query1="select * from State where Country=".$Country;
			$stmt = $db->prepare($query1);
			$stmt->execute();
			if ($stmt->rowCount()) {
                           while ($row = $stmt->fetch()) {

        echo "<option value='".$row['id']."' >".$row['State_name']."</option>";
        } } ?>

Now you can get dependent drop-down on selection of Country it will fetch the states across the country