简体   繁体   中英

how do i pass the php parameter using Javascript

I have created an html form. it consist of several drop down list for (countries,states,cities,areas)

the drop down list for countries looks like this.

Select Countries : <select name="countries" id="countries" onchange="showStates()">
<?php
foreach($crud->getAll('countries') as $countries) 
{ 
?>
    <option value="<?php echo $countries['id']; ?>"><?php echo $countries['name']; ?></option>
<?php } ?>
</select>

and the drop down list for states look like this.

Select State : <select name="states">
<?php
foreach($property->getStatesFromCountryId($countryId) as $states) 
{ 
?>
    <option value="<?php echo $states['id']; ?>"><?php echo $states['name']; ?></option>
<?php } ?>
</select>

the countries drop down list will fetch all the countries from the database and populate it. but in the states drop down list it needs the parameter to be passed dynamically from the country value.

for that i would like to achieve the following

1) hold the id of the country from the countries drop down list in a javascript countryId variable. the code should look something like this var countryId = document.getElementById("countries").value;

2) pass the parameter to foreach($property->getStatesFromCountryId($countryId) as $states) from countryId variable.

how do i achieve it?

Three ways I can think of to do this:

  1. Store all the states for every country in a big JS file as a JS object. Then read from this during the onChange event on the country dropdown.

  2. Store all the states serverside, use AJAX (XMLHttpRequest) to dynamically retrieve the states for the chosen country.

  3. Submit your form in the onChange, passing in a hidden variable to signify to your serverside script it should only fill the State dropdown, not do the rest of the validation yet.

看看这个问题: php下拉菜单填充

Few thoughts on kander's solutions:

  1. Ugly, but it can work offline. You can generate big JS object with PHP
  2. This one is probably the best solution. You can write very small PHP script like json_encode($crud->getAll(isset($_GET['country']? $_GET['country'] : '')); and have the JavaScript object ready to create second dropdown in no time.
  3. This is the failsafe for the 2nd.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM