You can send http requst because PHP is a server side language, and JavaScript is a client-side language. JavaScript runs in the browser, while PHP runs on the server.
Create a script like this to send response in json
class TestClass {
public function TestFunction() {
return "TESTING";
}
}
$testClass = new TestClass();
if (isset($_GET['action']) && $_GET['action'] === 'callTestFunction') {
$result = $testClass->TestFunction();
echo json_encode(["result" => $result]);
}
In html file,
<script>
$(document).ready(function() {
$.ajax({
url: 'TestClass.php?action=callTestFunction',
method: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.result); // Output--"TESTING"
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
});
</script>
and Ok make sure to add this above the script in html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>