I have a combobox that has data fetched from the database. When an index is selected from the combobox, a textbox value then gets a value from the database depending on the index selected from the combobox. I have with the following codes.
<form action = '' method = "POST">
<b> School ID: </b><br />
<select name = "school_id" required id = "schoold_id" onchange="get_data(this.value)">
<option value = "" selected></option>
<?php
$sql = "SELECT DISTINCT school_id FROM school";
$result = $db->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<option value = ".$row["school_id"].">".$row["school_id"]."</option>";
}
}
?>
</select><br /><br />
<b> Batch Number: </b><br />
<input type= "text" name = "batch_no" /required><br /><br />
<b> School Name: </b><br />
<input type= "text" name = "school_name" /readonly><br /><br />
<input type = "submit" value = " Submit "/><br />
</form>
The combobox here is the school id and the textbox that needs to be changed is the school name.
I tried using javascript and here it is that I used.
<script>
function get_data(value){
$.ajax({
url: "ajax.php",
type: "POST",
dataType: "HTML",
async: false,
data: {value: value}
success: function(data) {
//here we can populate the required fields based on value from database
}
});
}</script>
and this is the ajax file
<?php
include "connect.php";
$myschoolid = (filter_input(INPUT_POST, 'school_id'));
$sql = $db->prepare('SELECT school_name FROM main where school_id = ?');
$sql->bind_param('i', $myschoolid);
$sql->execute();
$result = $sql->get_result();
if ($result->numrows >0){
while ($row = $result->fetch_assoc()){
$newschoolid = $row["school_name"];
}
echo $newschoolid;
}
?>
I'm probably doing something wrong here. I'm not entirely familiar with ajax. Would appreciate help.