You are currently viewing JavaScript Cheat Sheet 11.1.3: AJAX – Server Response

JavaScript Cheat Sheet 11.1.3: AJAX – Server Response

AJAX – Server Response

AJAX (Asynchronous JavaScript and XML) is a technique used in web development to send and receive data from a server asynchronously without interfering with the display and behavior of the existing page. In this tutorial, we will focus on understanding how to handle server responses in AJAX.

Understanding AJAX Server Response

When an AJAX request is made to a server, the server processes the request and sends back a response. The response can be in various formats like HTML, XML, JSON, or plain text. In this tutorial, we’ll focus on handling responses in JSON format.

Sample Code

Let’s create a simple HTML page with JavaScript to demonstrate AJAX server response handling. We’ll use JavaScript’s XMLHttpRequest object to make AJAX requests.

HTML Structure

Create an HTML file named index.html and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Server Response</title>
</head>
<body>
<h1>Server Response:</h1>
<p id="response"></p>

<script src="script.js"></script>
</body>
</html>

JavaScript Code

Create a JavaScript file named script.js and add the following code:

document.addEventListener("DOMContentLoaded", function() {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "example.php", true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                document.getElementById("response").innerHTML = "Name: " + response.name + "<br>Email: " + response.email;
            } else {
                document.getElementById("response").innerHTML = "Error: " + xhr.status;
            }
        }
    };

    xhr.send();
});

PHP File (example.php)

Create a PHP file named example.php and add the following code:

<?php
header("Content-Type: application/json");

$response = array(
    "name" => "John Doe",
    "email" => "john@example.com"
);

echo json_encode($response);
?>

Explanation

  1. HTML Structure: This is a basic HTML structure with a heading and a paragraph element to display the server response. We include a <script> tag to link our JavaScript file.
  2. JavaScript Code:
  • We use document.addEventListener("DOMContentLoaded", function() {...} to ensure that the JavaScript code runs after the DOM is fully loaded.
  • We create a new XMLHttpRequest object to make an AJAX request.
  • xhr.open("GET", "example.php", true) initializes the request. We specify the URL of the server-side script (example.php) and set the request to be asynchronous.
  • xhr.onreadystatechange event handler listens for changes in the request state. When the request is completed (xhr.readyState === XMLHttpRequest.DONE), we check if the status is OK (xhr.status === 200).
  • If the status is OK, we parse the JSON response (xhr.responseText) and display the data in the paragraph element.
  • If there’s an error, we display the error status.
  1. PHP File:
  • This PHP script (example.php) is responsible for generating the server response.
  • We set the Content-Type header to application/json to indicate that the response will be in JSON format.
  • We create an associative array $response with sample data (name and email).
  • We encode the array as JSON using json_encode() and echo the JSON response.

Running the Example

  1. Save all the files (index.html, script.js, and example.php) in the same directory.
  2. Start your web server.
  3. Open index.html in a web browser.
  4. You should see the server response displayed on the webpage.

Conclusion

In this tutorial, you learned how to handle server responses in AJAX using JavaScript. We demonstrated making an AJAX request, processing the JSON response, and updating the webpage dynamically. AJAX server response handling is a fundamental aspect of web development, enabling interactive and dynamic user experiences. Experiment with different server responses and expand your understanding of AJAX capabilities.

Leave a Reply