I have an HTML form that runs a Javascript function on page load. In the Javascript function, a town name is sent via Ajax post call to Php function to get details from MySql database.
Ajax call in JavaScript function
var town = "Town name"; //depends on the previous execution in JS function
if (town != "undefined") {
jQuery.ajax({
type: "POST",
url: '../model/data_access/GetCity.php',
dataType: 'json',
data: {town: town},
success: function (obj) {
document.getElementById("selectedLocation").value = obj[0]["name"];
document.getElementById("placeDescriptionBox").value = obj[0]["description"];
}
});
}
GetCity.php
$town = $_POST['town'];
get_city($town);
function get_city($town)
{
$place = array();
$db_conn = DBConnection::get_database_connection();
$stmt = $db_conn->prepare("SELECT * FROM place WHERE name=?");
$stmt->bind_param("s", $town);
$stmt->execute();
if (!($result = $stmt->get_result())) {
echo "Error" . $stmt->error;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$place[0] = new Place();
$place[0]->set_name($row["name"]);
$place[0]->set_description($row["description"]);
echo json_encode($place);
}
}
The data from database are not displayed in the HTML form. How can I solve this?
I'm new to Ajax JQuery so any help is much appreciated.
Copyright License:
Author:「Fleur」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/37342687/ajax-jquery-post-code-with-php-to-query-mysql-database-not-working