I am always catching errors when sending an async request from my client-side javascript to my web-service php code. No guarantee that I used those terms correctly but I tried. It always catches an error and I think that the php code is not even being called.
function suggestSearch() {
var value = document.getElementById("filterText").value; //Suchtext
let reqObj = {method: "getNames", input: value};
fetch("actions/async_search.php", {method:"POST",body:JSON.stringify(reqObj)})
.then((response) => {
if(response.ok) {
let contentType = response.headers.get("content-type");
if(contentType && contentType.indexOf("application/json") != -1) {
return response.json();
}
}
throw new Error("Error in response!");
})
.then((result) => {
for(var i = 0; i < result.length; i++) {
var obj = result[i];
console.log(obj.id);
}
})
.catch( (error) => { alert("An error occured!" + error);
})
}
async_search.php:
header("Content-Type: application/json");
$result = ["result" => null];
$request = file_get_contents("php://input");
if(isset($request) && !empty($request)) {
$requestObj = json_decode($request);
if($requestObj->method == "getNames") {
$input = $requestObj->input;
if($input != "") {
$sql = "SELECT ArtikelName FROM artikel WHERE ArtikelName LIKE ? LIMIT 5;";
$statement = $conn -> prepare($sql); //prepare
$statement -> execute(array("$input%"));
$result = $statement -> fetchall(PDO::FETCH_ASSOC);
echo json_encode($result);
}
}
}
// EDIT : Now I came so far that I get this as an error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I have found the error. When saving to the $result array I have to put the variables in brackets, eg
$result = ["result" => ($row['ArtikelName']), "info" => "Ok"];
before encoding it. I hope this helps someone in the future.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.