I have a form where i need to get data in a text box when user selects a place. If the user chooses a place then the following name and amount will come in the following textbox. I have done the following but it is not working. Can anyone please help me with this?
I have tried the following:
HTML
<div>
<label for="" class="">Place</label>
<select name="place" id="place" onchange="myplace();">
<option value="">--Option from db--</option>
</select>
</div>
<div>
<label for="" class="">Name</label>
<input type="text" name="myname" id="myname" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >
</div>
<div>
<label for="" class="">Amount</label>
<input type="text" name="myamnt" id="myamnt" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >
</div>
MySQL:
if(!empty($_POST["myinitplace"]))
{
$sql = "SELECT * FROM all_data , my_place WHERE all_data.place=my_place.place and all_data.place = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST["myinitplace"]);
$stmt->execute();
$result = $stmt->get_result();
while($rows = $result->fetch_assoc())
{
$data['name']=$rows['name'] ;
$data['myacc']=$rows['amount'] ;
}
echo json_encode($data);
}
Ajax
function myplace()
{
var a = document.getElementById("place").value;
//alert(a);
$.ajax({
type : "POST",
data : {
myinitplace : a
},
dataType : "JSON",
success : function(data){
document.getElementById("myname").value = data.name;
document.getElementById("myamnt").value = data.myacc;
}
})
}
2
Answers
First of all, I assume that you have populated the select block with valid data in the following line:
such as
In that case, you need to slightly amend your HTML code so that it explicitly calls the PHP script (by specifying the url), so add the line in the ajax block:
Assuming that the PHP script’s name is
testSO3Sept2023.php
, then the HTML will be:You may view the result by this sandbox