rewrite API call

This commit is contained in:
Remo Zaros
2026-06-10 09:11:28 +02:00
parent 558ea24cec
commit 0ba7c07287

View File

@@ -24,6 +24,8 @@ function modal_styles()
wp_enqueue_style(
"prijs-per-postcode",
plugins_url("/assets/postcode_modal.css", __FILE__),
[], // Voeg een lege dependencies array toe (verplicht)
filemtime(plugin_dir_path(__FILE__) . "assets/postcode_modal.css"), // Voeg versie toe
);
}
@@ -48,24 +50,28 @@ function send_postcode_data()
const sndBtnTxt = sndBtn.querySelector(".btn_text");
const errorMsg = document.querySelector("#error_message_modal_postcode");
// 1. Validatie bij blur (client-side checks)
modalForm.querySelectorAll("input").forEach(input => {
input.addEventListener("blur", ev => {
errorMsg.innerHTML = ""
if(!ev.target.validity.valid && ev.target.value !== "") {
errorMsg.innerHTML = "";
if (!ev.target.validity.valid && ev.target.value !== "") {
errorMsg.innerHTML = ev.target.title;
}
})
})
});
});
// 2. Submit Handler
modalForm.addEventListener('submit', async (e) => {
e.preventDefault();
errorMsg.innerHTML = "";
// UI: Laadstatus
sndBtn.disabled = true;
sndBtnLdr.style.opacity = "1";
sndBtnTxt.style.opacity = "0";
const formData = new FormData(e.target);
const data = Object.fromEntries(formData.entries());
const json = JSON.stringify(data);
const payload = Object.fromEntries(formData.entries());
try {
const resp = await fetch('<?php echo get_rest_url(
@@ -76,44 +82,60 @@ function send_postcode_data()
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': '<?php echo wp_create_nonce("wp_rest"); ?>'
'X-WP-Nonce': '<?php echo wp_create_nonce(
"wp_rest",
); ?>'
},
body: json
body: JSON.stringify(payload)
});
if(!resp.ok){
throw new Error(`HTTP Error! status: ${resp.status}` );
}
// Parse altijd eerst de JSON, zelfs bij HTTP fouten
const data = await resp.json();
// UI: Reset knop
sndBtn.disabled = false;
sndBtnLdr.style.opacity = "0";
sndBtnTxt.style.opacity = "1";
const data = await resp.json();
console.log("Data returnd", data);
if (data.status === "error"){
const err = data.code;
let errmsg
if (data.status === "error") {
const errorCode = data.code; // Komt nu correct door vanuit PHP
const apiMessage = data.message;
switch (err) {
case "HUISNUMMER_NOT_FOUND":
errmsg = "Adres is niet gevonden.";
break;
case "HUISNUMMER_AMBIGUOUS":
errmsg = "Huisnummertovoeging mist.";
break;
default:
errmsg = "Gegevens zijn niet correct.";
let userErrorMessage = "Gegevens zijn niet correct.";
// Specifieke foutafhandeling
if (errorCode === "HUISNUMMER_NOT_FOUND" || apiMessage.includes("not found")) {
userErrorMessage = "Adres is niet gevonden.";
}
errorMsg.innerHTML = errmsg;
else if (errorCode === "HUISNUMMER_AMBIGUOUS") {
// Deze komt ALLEEN nog hier als PHP géén 'platte' match kon vinden.
// Dat betekent dat de gebruiker verplicht een toevoeging moet geven (bijv. alleen 15A bestaat).
const suggestions = data.suggestions || [];
if (suggestions.length > 0) {
userErrorMessage = `Meerdere opties: ${suggestions.join(", ")}. Voeg een toevoeging toe.`;
} else {
userErrorMessage = "Huisnummertoevoeging is verplicht.";
}
}
else if (errorCode === "CURL_ERROR" || errorCode === "JSON_ERROR") {
userErrorMessage = "Serverfout. Probeer het later opnieuw.";
}
if (data.status === "success"){
errorMsg.innerHTML = userErrorMessage;
}
if (data.status === "success") {
// Succes: Modal sluiten en eventueel reload of update
postcodeModal.close();
//location.reload();
// Optioneel: location.reload(); of update de pagina content
}
}catch(err){
} catch (err) {
console.error("Fetch Failed:", err);
throw err;
sndBtn.disabled = false;
sndBtnLdr.style.opacity = "0";
sndBtnTxt.style.opacity = "1";
errorMsg.innerHTML = "Er ging iets mis bij het verbinden.";
}
});
</script>
@@ -180,56 +202,99 @@ function handle_postcode_modal($data)
$params = $data->get_params();
$nonce = $data->get_header("X-WP-Nonce");
if (wp_verify_nonce($nonce, "wp_rest")) {
// 1. Security
if (!wp_verify_nonce($nonce, "wp_rest")) {
echo json_encode(["status" => "error", "message" => "nononce"]);
exit();
}
// 2. Basis Validatie
if (!verify_postcode($params["postcode"])) {
$resp = [
"status" => "error",
"message" => "postcode",
];
echo json_encode($resp);
echo json_encode(["status" => "error", "message" => "postcode"]);
exit();
}
if (!verify_huisnummer($params["huisnummer"])) {
$resp = [
"status" => "error",
"message" => "huisnummer",
];
echo json_encode($resp);
echo json_encode(["status" => "error", "message" => "huisnummer"]);
exit();
}
// 3. API Call (Ruwe data)
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
if (isset($result["error"])) {
$resp = [
// 4. Validatie & Logic
$hasError = isset($result["error"]);
$errorCode = null;
$errorMessage = null;
$candidates = [];
$straatnaam = null;
$woonplaats = null;
if ($hasError) {
$errorCode = $result["error"]["code"] ?? "UNKNOWN_ERROR";
$errorMessage = $result["error"]["message"] ?? "Onbekende fout";
$candidates = $result["error"]["details"]["candidates"] ?? [];
// SPECIAL CASE: HUISNUMMER_AMBIGUOUS
if ($errorCode === "HUISNUMMER_AMBIGUOUS" && !empty($candidates)) {
$plainMatch = null;
// Zoek naar candidate ZONDER toevoeging
foreach ($candidates as $candidate) {
if (
empty($candidate["huisletter"]) &&
empty($candidate["huisnummertoevoeging"])
) {
$plainMatch = $candidate;
break;
}
}
// Als we een 'platte' match hebben (bijv. 15), dan is het SUCCES
if ($plainMatch) {
$hasError = false; // Negeer de error
$straatnaam = $plainMatch["straat"];
$woonplaats = $plainMatch["woonplaats"];
}
}
} else {
// Normaal succes (geen error in response)
if (!empty($result["results"])) {
$straatnaam = $result["results"][0]["straat"];
$woonplaats = $result["results"][0]["woonplaats"];
} else {
// Edge case: geen error veld, maar ook geen results
$hasError = true;
$errorCode = "NO_RESULTS";
$errorMessage = "Adres niet gevonden";
}
}
// 5. Response sturen
if ($hasError) {
echo json_encode([
"status" => "error",
"message" => $result["error"],
"code" => $errorCode,
"message" => $errorMessage,
"suggestions" => $result["error"]["details"]["suggestions"] ?? [],
"apirequest" => "openpostcode.nl",
];
echo json_encode($resp);
]);
exit();
}
// 6. Succes: Sessie opslaan & response
$_SESSION["postcode"] = $params["postcode"];
$_SESSION["huisnummer"] = $params["huisnummer"];
$_SESSION["straatnaam"] = $result["straatnaam"];
$_SESSION["woonplaats"] = $result["woonplaats"];
$_SESSION["straatnaam"] = $straatnaam;
$_SESSION["woonplaats"] = $woonplaats;
$_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]);
$resp = [
echo json_encode([
"status" => "success",
"message" => "all good",
"straatnaam" => $result["straatnaam"],
"lokaal_trarief" => postcode_in_range($params["postcode"]),
];
} else {
$resp = [
"status" => "error",
"message" => "nononce",
];
}
echo json_encode($resp);
"straatnaam" => $straatnaam,
"woonplaats" => $woonplaats,
"lokaal_tarief" => postcode_in_range($params["postcode"]),
]);
exit();
}
@@ -272,27 +337,32 @@ function getStraatnaam($postcode, $huisnummer)
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_error($ch)) {
curl_close($ch);
return ["error" => "cURL error: " . curl_error($ch)];
return [
"error" => ["code" => "CURL_ERROR", "message" => curl_error($ch)],
];
}
curl_close($ch);
// Decodeer als associatieve array (true)
$data = json_decode($response, true);
if (isset($data["error"])) {
// Als JSON decode faalt
if (json_last_error() !== JSON_ERROR_NONE) {
return [
"error" => $data["error"]["message"],
"code" => $data["error"]["code"],
"error" => [
"code" => "JSON_ERROR",
"message" => "Invalid JSON response",
],
];
}
return [
"straatnaam" => $data["results"][0]["straat"],
"woonplaats" => $data["results"][0]["woonplaats"],
];
// Geef de RUWE response terug (inclusief meta, error, results, etc.)
return $data;
}
function postcode_in_range($postcode)