[英]auto fill input text boxes using AJAX and PHP and Javascript
我有一個選擇框,其中包含使用數據庫(phpmyadmin)的數據生成的選項,數據庫如下所示:
Columns: locationID - address - postalcode - place
在選擇框之后,我有一些輸入字段,最初是帶有一些占位符的標准字段。
這個想法是,如果我選擇一個選項,將從數據庫中生成並填充字段(“ contactperson
字段除外,這將保持手動狀態)。
為此,我嘗試使用AJAX。
我已經做了這個:
test.php :
<?php
//Query the database for the results we want
$query1 = $conn->query("SELECT * FROM deliveryaddress");
//Create an array of objects for each returned row
while($locationArray[] = $query1->fetch_object());
//Remove the blank entry at end of array
array_pop($locationArray);
?>
<script>
$(document).on("change","#select-box").function(){
var id = $(this).val();
$.ajax({
url : "locationAjax.php",
data : {"id":id},
type : "POST",
dataType : "HTML",
success : function(data){
// here you can write code to asign the values to text boxes.
$(".wrapperDiv").html(data);
}
});
});
</script>
<div class="wrapperDiv">
<label for="locationLabel">Locatie</label>
<select name="locations" id="locationSelectBox" >
<option>Locatie</option>
<?php foreach ($locationArray as $option) : ?>
<option value="<?php echo $option->locationID; ?>"><?php echo $option->locationID; ?></option>
<?php endforeach; ?>
</select>
<label for="address" style="float:left;">Straat/No</label>
<input type="text" name="address" id="address" placeholder="Straatnaam en nummer" />
<label for="postalCode">Postcode</label>
<input type="text" name="postalCode" id="postalCode" placeholder="Postcode" />
<label for="place">Plaats</label>
<input type="text" name="place" id="place" placeholder="Plaats" />
<label for="contactPerson">Contact</label>
<input type="text" name="contactPerson" id="contactPerson" placeholder="Contactpersoon" />
</div>
locationAjax.php :
<?php
require_once('dbconnection.php');
$locationID = $_POST['id'];
$sql = "SELECT * FROM deliveryaddress where id = $locationID";
$result = mysqli_query($conn, $sql);
?>
<?php while ($row = mysqli_fetch_assoc($result)) { ?>
<input type="text" name="name" value="<?= $row['address'] ?>" />
<input type="text" name="name" value="<?= $row['postalcode'] ?>" />
<input type="text" name="name" value="<?= $row['place'] ?>" />
}
?>
不幸的是,它不起作用。
代替此行:$(document).on(“ change”,“#select-box”)。function(){
試試這個:$(document).on(“ change”,“#locationSelectBox”)。function(){
然后console.log關於ajax“成功”功能的數據,告訴我你得到了什么
嘗試這個
echo json_encode(mysqli_fetch_assoc($result));
在腳本循環中,控制台日志數據可查看結果以進行故障排除
將腳本更改為
$(document).on("change", "#locationSelectBox").function() {
var id = $(this).val();
$.ajax({
url : "locationAjax.php",
data : {
"id" : id
},
type : "POST",
dataType : "json",
success : function(data) {
console.log(data);
//
for (var x in data) {
$('.address').val(data.address);
$('.postalcode').val(data.postalcode);
$('.place').val(data.place);
}
}
});
});
檢查您的控制台日志中的錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.