How to use AJAX to populate the list of states depending on the list of countries?

I have the code below that will change the status dropdown when changing the list of countries.
How can I make it change the state list ONLY when country identifiers 234 and 224 are selected?
If another country is selected, it must be changed in this text entry field.

<input type="text" name="othstate" value="" class="textBox">

The form

<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>

javascript

<script>
function getState(countryId)
{
   var strURL="findState.php?country="+countryId;
   var req = getXMLHTTP();
   if (req)
   {
     req.onreadystatechange = function()
     {
      if (req.readyState == 4)
      {
     // only if "OK"
     if (req.status == 200)
         {
        document.getElementById('statediv').innerHTML=req.responseText;
     } else {
       alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
       }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}
</script>
+3
source share
5 answers

countryId AJAX , countryId . , countryId , (, ) , . , .

jQuery :

<form method="post" name="form1">
   <select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
      <option>Select Country</option>
      <option value="223">USA</option>
      <option value="224">Canada</option>
      <option value="225">England</option>
      <option value="226">Ireland</option>
   </select>

   <select style="background-color: #ffffa0" name="state">
      <option>Select Country First</option>
   </select>

   <input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>

$(function() {
    $('#country').change( function() {
        var val = $(this).val();
        if (val == 223 || val == 224) {
            $('#othstate').val('').hide();
            $.ajax({
               url: 'findState.php',
               dataType: 'html',
               data: { country : val },
               success: function(data) {
                   $('#state').html( data );
               }
            });
        }
        else {
           $('#state').val('').hide();
           $('#othstate').show();
        }
    });
});
+4

, - . none, getState()

if (countryId == 233 || countryId == 234) {
   /* Ajax state population here */

   dropdownId.display = 'block';
   textEntryId.display = 'none';
}
else  {
   textEntryId.display = 'block';
   dropdownId.display = 'none';
}

( dropdownId textEntryId ), / .

JQuery , .

+1

EDIT: , , Tvanfosson:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>

<script>
$(function() {
  $('#country').change( function() {
    var val = $(this).val();
    if (val == 223 || val == 224) {
        $('#othstate').val('').hide();
        $.ajax({
           url: 'findState.php',
           dataType: 'html',
           data: { country : val },
           success: function(data) {
               $('#state').html( data );
           }
        });
    }
    else {
       $('#state').val('').hide();
       $('#othstate').show();
    }
  });
});
</script>

<select style="background-color: #ffffa0" name="country" id=country >
  <option>Select Country</option>
  <option value="223">USA</option>
  <option value="224">Canada</option>
  <option value="225">England</option>
  <option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
  <option>Select Country First</option>
</select>

<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">

As you can see, I excluded the element <form>, which is not absolutely necessary, but can be added (and then should be used correctly if JS is deactivated at the end of the user. Here .

I also excluded the event onchange, which is replaced by the jQuery 'change () function.

+1
source

API VK just select a country, enter it and select a city from

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
    
var $j = jQuery.noConflict();
var _getCountry = function() {
    $j.ajax({
      url: "http://api.vk.com/method/database.getCountries",
      data: {
       'v': 5.5,
        'need_all': 0,
        'code' : 'RU,UA,BY,KZ,KG,LV,EE'  
       // 'count': 10
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each country");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         country_options.push(newOption);
       });
    
       document.getElementById('countrylist').innerHTML = country_options;
          
      }
        
 });  
 }   

var _getCity = function(country_id) {
     
    $j.ajax({
      url: "http://api.vk.com/method/database.getCities",
      data: {
       'v': 5.61,
        'need_all': 0,
        'country_id': country_id
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each city");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         city_options.push(newOption);
       });
    
       document.getElementById('citylist').innerHTML = city_options;
          
      }
        
 });  
 }  
       
var  city_options = [];
var  country_options = [];
    
 $j(document).ready(function () {  
    _getCountry(); 
     
  $j('#country').on('input',function() {
    var opt = $j('option[value="'+$j(this).val()+'"]');
    var countryid = opt.attr('id');  
      
    _getCity(countryid);  
      
     
  });

  
 });

</script>
 <div class="form-group">
          <label class="col-lg-4 control-label">:</label>
          <div class="col-lg-8">
          
              <div class="controls">
            	<input name="country" list="countrylist" id="country" class="form-control" />
                <datalist id="countrylist">
                </datalist> 
              </div>
        
           
           
            
          </div>
        </div> 
   
        <div class="form-group">
          <label class="col-lg-4 control-label">:</label>
          <div class="col-lg-8">
                
            <input name="city" list="citylist" id="city" class="form-control"/>
                <datalist id="citylist">
            </datalist>  
              
           
          </div>
        </div> 
Run codeHide result
0
source
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = '';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         mysql_select_db( 'testajax' );
?>

/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php 
include('con.php');
?>
<form>
<div class="frmDronpDown">
    <div class="row">
        <table><tr><td><label>Country:</label><br/>
        <select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct country FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
        <?php
        }
        ?>
        </select> </td>
             <td>
<label>Phone:</label><br/>
        <select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct phone FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
        <?php
        }
        ?>
        </select> 
</td></tr></table>
    </div>
    <div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
        var dataname = $('#country').attr('data-name');

        console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}

function getPhone(val) {
        var dataname = $('#phone').attr('data-name');

    console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                 value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}
</script>

// ////////////////////data file data.php rishabh
<?php 
$val = $_POST["value_name"]; 
$colomn = $_POST["colomn_name"]; 
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
  <table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>
0
source

Source: https://habr.com/ru/post/1713595/


All Articles