/* retrieve search*/
const retrieveSearchUISuccess = function (info) {
displaySearch(info);
};
/* If Database Table fails to load or what have you */
const retrieveSearchUIError = function (error) {
console.log("Database Table did not load", error);
};
/* Call Fetch Search */
const callSearch = (retrieveUrl, succeed, fail) => {
fetch(retrieveUrl, {
method: 'POST', // or 'PUT'
body: JSON.stringify(text)
})
.then((response) => handleErrors(response))
.then((data) => succeed(data))
.catch((error) => fail(error));
};
/* Handle General Errors in Fetch */
const handleErrors = function (response) {
if (!response.ok) {
throw (response.status + ' : ' + response.statusText);
}
return response.json();
};
const s = document.querySelector("#searchText");
s.addEventListener("keyup", function() {
let text.value = s.value; // I usually make this a global variable as it's a couple layers deep
callSearch('getClient.php', retrieveSearchUISuccess, retrieveSearchUIError);
});
dataType just tells jQuery’s response handler how to process the result - so in vanilla you don’t do that, you just handle it in whatever way you need to (response.text())
data… there’s a couple ways to go about it, but there’s an example of one way in Pepster’s post:
I believe from context clues at that point text is an element reference to a text field.
Two notes:
1: content-type should be intelligent and not necessarily need to be set by you; YMMV.
2: you should also be able to pass something like new URLSearchParams(new FormData(yoursearchfield)) as the body parameter, and get a multipart/form-data content type instead.
Thanks. I think I’m getting somewhere one step at a time. So it’s the ‘body’ that gets sent, so now I need to figure how to send it as $_POST['search_name'].
When using the Fetch API to send data to a PHP server, you’ll have to handle the request a little differently from what you’re used to.
The data you’re POSTing is not going to be available in the super global variables since this input is not coming from a multipart-data form or an application/x-www-form-urlencoded.
There are a number of ways around this, but the easiest path here is to send the data as FormData. Here is a simple example for you to play around with:
This just echos the search term right back at you, but hopefully it is enough to demonstrate the concept.
Another thing you might want to think about when you’ve got this working is to debounce the keyup event, so that your server is not hammered by requests on every keystroke.