I’m trying to get data from the database using ajax to insert it in other element but the post data not passing to get-data.php
so what the reason can be and the solution
addBuilding.php
<?php
require_once("./dbConfig.php");
$selectIL = "SELECT * FROM iller ";
$selectIL = $db->prepare($selectIL);
$selectIL->execute();
$res = $selectIL->get_result();
?>
<form action="" method="post">
<select name="pp" id="cites">
<option value="">-select state-</option>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['il_adi'] ?></option>
<?php
}
?>
</select>
<select name="district" id="district">
<option value="">-select district-</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="getdata.js"></script>
getdata.js
$(document).ready(function() {
$("#cites").change(function() {
if ( $("#cites").val()!="") {
$("#district").prop("disabled",false);
}else {
$("#district").prop("disabled",true);
}
var city = $("#cites").val();
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
success: function(result) {
$("#district").append(result);
}
});
});
});
get-data.php
I can see the form data in network inspection put no data passing to get-data.php
<?php
require_once("./dbConfig.php");
if (isset($_POST['pp'])) {
$cites = $_POST['cites'];
$selectIlce = "SELECT * FROM ilceler where il_id=? ";
$selectIlce = $db->prepare($selectIlce);
$selectIlce->bind_param("i", $cites);
$selectIlce->execute();
$res = $selectIlce->get_result();
?>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['ilce_adi'] ?></option>
<?php
}
}
?>
2
Answers
You need to echo the results in get-data.php
1- Get data by serialize from form:
2- Add dataType: "json" to ajax option: