To interact with PHP through AJAX, you can use the `XMLHttpRequest` object in JavaScript to send an HTTP request to a PHP file on the server. Here’s an example:




JavaScript (script.js):
function getData() {
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
document.getElementById(“result”).innerHTML = xhr.responseText;
} else {
};“GET”, “getData.php”, true);

PHP (getData.php):


In this example, when the “Get Data” button is clicked, the `getData()` function is called which creates a new `XMLHttpRequest` object. The `onreadystatechange` event handler function is set to handle the response from the server.

The `` method is used to set up the HTTP request. Here, we are making a GET request to the `getData.php` file. The `xhr.send()` method is used to send the request to the server.

When the server responds, the `onreadystatechange` event handler function is called. Inside it, we check if the request is complete (readyState === XMLHttpRequest.DONE) and if the response status code is 200 (HTTP OK). If both conditions are met, we update the `result` element with the response text.

Note that the PHP file (getData.php) can contain any PHP logic required, such as fetching data from a database or performing calculations. The response from the PHP file is sent back to the JavaScript code as plain text, which can be used to update the webpage.