I have 2 select box option, city and district. I use ajax go get district name when I choose on the city. For this process I have succeed but when I click submit I get the error message Undefined index: district ,as this picture you can see result image .
Here is my ajax code:
$(document).ready(function($) {
$("#city").change(function() {
var search_id = $(this).val();
$.ajax({
url: "search.php",
method: "post",
data: {search_id:search_id},
success: function(data){
$("#district").html(data);
}
})
});
});
Here is HTML code:
<form action="" method="post"> select city: <select name="city" id="city"> <option value="1">Phnom Penh</option> <option value="2">Kampong Soam</option> <option value="3">Siem Reap</option> </select> select district: <select name="distrcit" name="district" id="district"> <option>Select District</option> </select> <input type="submit" name="submit"> </form>
Here is PHP code:
<?php if(isset($_POST['submit'])){ echo $_POST['city']; echo $_POST['district']; } ?> //ajax request <?php if(isset($_POST['search_id'])){ $search_id = $database->escape_string($_POST['search_id']); if(!empty($search_id)){ // $output = array(); $sql = "SELECT * FROM district WHERE ref_id = '$search_id'"; $districts = District::find_this_query($sql); foreach($districts as $district){ // echo $district->id; // echo $district->district_name; $output .= "<option value='{$district->id}'>{$district->district_name}</option>"; } echo $output; } } ?>
You have set name twice in select box. assign name only once:
so make it:
<select name="district" id="district">
<option>Select District</option>
</select>
In the HTML you have declared name attributes 2 times:
<select name="distrcit" name="district" id="district">
Please replace with:
<select name="district" id="district">
我认为这种方式不是很干净,您可以创建一个 ajax 请求以 json 格式返回值,然后使用
new Option(text, value);
please define name one time only :
<select name="district" id="district">
<option>Select District</option>
<form action="" method="post"> select city: <select name="city" id="city"> <option value="1">Phnom Penh</option> <option value="2">Kampong Soam</option> <option value="3">Siem Reap</option> </select> select district: <select name="distrcit" name="district" id="district"> <option>Select District</option> </select> <input type="submit" name="submit"> </form>
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.