I need help desperately…
I have this website: Horoskop Paradies. On this page I have a form that allows users to generate a horoscope on demand. In the form I have an input called, “Geburtsort”, which means “Place of birth”. When the user starts typing in the input, a list of suggested locations appear from a SQL database (that I own). It works most of the time, but not when the city name has special characters like “ü” etc. For example, “Cape Town” works, but not “Äbigrub”. I tried this on my local system using XAMPP and it works perfectly, but in production it does not. Try the live site for context, I also added some logs in the console.
Here is the relevant JS code:
placeOfBirthInput.addEventListener("input", async function () {
const place = placeOfBirthInput.value;
if (place) {
const suggestions = await getLocationSuggestions(place);
displaySuggestions(suggestions);
} else {
clearSuggestions();
}
});
suggestionsDiv.addEventListener("click", function (event) {
if (event.target.classList.contains("suggestion")) {
selectedPlace = {
name: event.target.getAttribute("data-name"),
countryCode: event.target.getAttribute("data-countryCode"),
latitude: event.target.getAttribute("data-latitude"),
longitude: event.target.getAttribute("data-longitude"),
timezone: event.target.getAttribute("data-timezone"), // Add timezone
};
placeOfBirthInput.value = selectedPlace.name;
latitudeInput.value = selectedPlace.latitude; // Update latitude value
longitudeInput.value = selectedPlace.longitude; // Update longitude value
timezoneInput.value = selectedPlace.timezone; // Update timezone value
clearSuggestions();
}
});
async function getLocationSuggestions(place) {
try {
console.log("Place being sent for location suggestions:", place); // Log the place being sent
const requestBody = "search=" + encodeURIComponent(place);
console.log("Request Body:", requestBody); // Log the request body
const response = await fetch(
'https://api-horoskop-paradies.com/api.horoskop-paradies.ch/astrology/geoname.php',
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "search=" + encodeURIComponent(place),
}
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const contentType = response.headers.get("content-type");
const responseBody = await response.text(); // Read the response body once
console.log("Response Body:", responseBody); // Log the response body
// Check if the response body is empty
if (responseBody.trim() === '') {
console.log("Empty response body received.");
return []; // Return an empty array
}
// Parse the JSON response body
const suggestions = JSON.parse(responseBody);
console.log("Parsed Suggestions:", suggestions); // Log the parsed suggestions
if (!suggestions || suggestions.length === 0) {
console.error("Invalid suggestions data:", suggestions);
return []; // Return an empty array or handle the error as needed
}
// Process the suggestions further if needed...
return suggestions; // Return the parsed suggestions
} catch (error) {
console.error("Error fetching location suggestions:", error);
return []; // Return an empty array or handle the error as needed
}
}
And here is the server PHP code (geoname.php)
<?php
define('DEBUG_MODE', true); // Set to true to enable debugging, false to disable
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json"); // Set response content type to JSON
// Database credentials
$servername = "localhost";
$username = "###";
$password = "###";
$database = "###";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
// Return error response if connection fails
echo json_encode(array('error' => 'Connection failed: ' . $conn->connect_error));
exit; // Terminate script execution
}
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['search'])) {
// Get the search parameter
$searchParam = urldecode($_POST['search']);
// Log the received search parameter
if (DEBUG_MODE) {
error_log("Received search parameter: " . $searchParam);
}
// Perform any necessary modifications or validations on the search parameter
// For example, you can trim whitespace or apply htmlspecialchars
$searchParam = trim($searchParam);
$searchParam = htmlspecialchars($searchParam);
$cityName = '%' . $searchParam . '%'; // Use wildcard for partial matching
// Log the modified search parameter
if (DEBUG_MODE) {
error_log("Modified search parameter: " . $cityName);
}
// Prepare and execute the database query
$stmt = $conn->prepare("SELECT * FROM `world_database_all_new` WHERE place LIKE ? ORDER BY place ASC LIMIT 8");
$stmt->bind_param("s", $_POST['search']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
// Return JSON response with data
echo json_encode($data);
} else {
// No results found
echo json_encode(array('error' => 'No results found for: ' . $_POST['search']));
}
} else {
// Invalid request
echo json_encode(array('error' => 'Invalid request'));
}
// Close database connection
$conn->close();
?>
Hoping to get some help please 🙂
Thanks!
I tried on my local system using XAMPP. It worked as expected, but in production it did not.