Open In App

How to get return text from PHP file with ajax ?

Last Updated : 06 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to get return the text from the PHP file with ajax. Ajax is an acronym for Asynchronous JavaScript and XML is a series of web development techniques that build asynchronous web applications using many web technologies on the client-side. Without reloading the web page, AJAX enables you to send and receive information asynchronously.

Approach: When the button gets clicked, we have initialized the XMLHttpRequest object, which is responsible for making AJAX calls. Then, we have to check if the readyState value is 4, which means the request is completed, and we have got a response from the server.

Next, we have checked if the status code equals 200, which means the request was successful. Finally, we fetch the response which is stored in the responseText property of the XMLHttpRequest object. After setting up the listener, we initiate the request by calling the open method of the XMLHttpRequest object. Then call the send method of the XMLHttpRequest object, which actually sends the request to the server. When the server responds, you can see the text displaying the response from the PHP file.

Example: This example describes returning the text from PHP with AJAX.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <button type="button" id="fetchBtn">Click Me!</button>
    <p id="txt"></p>
  
      
    <script>
    let fetchBtn = document.getElementById('fetchBtn');
    fetchBtn.addEventListener('click', buttonClickHandler);
  
    function buttonClickHandler() {
        
        // Instantiate an xhr object
        var xhr = new XMLHttpRequest();
        
        // What to do when response is ready  
        xhr.onreadystatechange = () => {
            if(xhr.readyState === 4) {
                if(xhr.status === 200) {
                    document.getElementById("txt").innerHTML = 
                    xhr.responseText;
                } else {
                    console.log('Error Code: ' + xhr.status);
                    console.log('Error Message: ' + xhr.statusText);
                }
            }
        }
        xhr.open('GET', 'data.php');
        
        // Send the request
        xhr.send();
    }
    </script>
</body>
  
</html>


PHP code: The following is the code for the “data.php” file used in the above HTML code.

data.php




<html>
<body>
   <?php echo '<h1>Welcome to GfG</h1>'; ?>  
</body>
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads