The code is okay because it was able get a success message in the console, however, the data in the input fields is not auto populating even there is no error. I’m using jquery-3.6.0.min.js. Here’s the code:
$(document).on('click', '.editResident', function() {
var resident_id = $(this).val();
$.ajax({
type: "GET",
url: "code.php?resident_id=" + resident_id,
success: function (response) {
console.log("Response received:", response);
var res = jQuery.parseJSON(response);
if(res.status == 404) {
alert(res.message);
}else if(res.status == 200){
var data = res.data;
$('#resident_id').val(data.ID);
$('#status').val(data.status);
$('#firstName').val(data.first_name);
$('#middleName').val(data.middle_name);
$('#lastName').val(data.last_name);
$('#gender').val(data.gender);
$('#civilStatus').val(data.civil_status);
$('#birthdate').val(data.birth_date);
$('#address').val(data.address);
$('#contactNum').val(data.contact_num);
$('#voter').val(data.voter);
$('#category').val(data.category);
$('#editResidentModal').modal('show');
$('#editResidentModal').on('shown.bs.modal', function (e) {
console.log("Edit Resident Modal is shown");
});
// Show the edit modal after populating fields
$('#editResidentModal').modal('show');
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
alert('Error occurred while fetching resident data. Please try again.');
}
});
});
I tried different methods but isn’t successful. I was expecting that when I click the edit button the corresponding data will auto-populate the edit form (each input fields). Here’s the PHP server side:
if (isset($_GET['resident_id'])) {
$resident_id = mysqli_real_escape_string($conn, $_GET['resident_id']);
$query = "SELECT * FROM resident_db WHERE ID='$resident_id'";
$query_run = mysqli_query($conn, $query);
if (mysqli_num_rows($query_run) == 1) {
$resident = mysqli_fetch_array($query_run);
$res = [
'status' => 200,
'message' => 'Data Fetch Successfully by id',
'data' => $resident
];
echo json_encode($res);
return;
} else {
$res = [
'status' => 404,
'message' => 'Resident Id Not Found'
];
echo json_encode($res);
return;
}
}