Handling Server Responses and Updating the Webpage

Intermediate

๐Ÿ“ฅ Handling Ajax Responses

Once an Ajax request is completed, handling the server response correctly is crucial to ensure a smooth user experience. Common response formats include JSON, XML, HTML, and plain text.


๐Ÿงช Example: Updating Content with JSON Data

fetch('api/data')
  .then(response => response.json())
  .then(data => {
    document.getElementById('result').innerHTML = `User: ${data.name}, Age: ${data.age}`;
  });

๐Ÿ“„ Handling Different Data Types

| ๐Ÿ—‚๏ธ Format     | ๐Ÿ“Œ Usage                                                             |
|---------------|----------------------------------------------------------------------|
| ๐Ÿงพ JSON       | Typical for data exchange; parsed into JavaScript objects            |
| ๐Ÿงฌ XML        | Used in legacy systems; parsed with DOM parsers                      |
| ๐Ÿงฑ HTML       | Directly inject into DOM as `innerHTML`                              |
| ๐Ÿ“ Plain Text | For simple messages or logs                                          |

๐Ÿ›ก๏ธ Proper parsing and validation are essential, especially with JSON and XML, to prevent security issues like XSS or malformed data errors.