If you want to call a PHP function from Javascript, you need to send an XMLHttpRequest to a server on which this function is running. Javascript is running in the browser, at your client computer. And PHP is running on your server, in some datacenter somewhere. Therefore, it's impossible to call a PHP function from your Javascript directly.
The XmlHttpRequest send an http request ( POST | GET | ... ) to a server and wait for it's output. In your case, you would call a php file on a server and wait for it's response.
From Javascript.info
// 1. Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL
xhr.open('GET', '/yourPhPfileLocationUrl/');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
There is also numerous libraries out there to do way simpler XMLHttpRequest.
You could also submit a form, it might be easier.
<form action="/yourPHPFunctionUrl">
<!-- some inputs -->
<button type="submit">Send me ! </button>
</form>