Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Ajax Response in JavaScript

Ajax Response in JavaScript

? AJAX Response in JavaScript

An AJAX response is the data that a server sends back to your JavaScript code after making an AJAX request. You can use this data to update the webpage dynamically without reloading it.


? Common Response Types

TypeDescriptionUsage Example
TextPlain text"Hello from server"
HTMLHTML code snippet"<p>Loaded content</p>"
JSONStructured data (key-value){"name": "John", "age": 25}
XMLOlder format for structured data<user><name>John</name></user>

? Example 1: Text Response (Using fetch())

HTML:

<button onclick="loadText()">Load Text</button><div id="result"></div>

JavaScript:

function loadText() {  fetch("message.txt")    .then(response => response.text())    .then(data => {      document.getElementById("result").innerHTML = data;    });}

Server File (message.txt):

Hello from the server!

? Example 2: JSON Response (Using fetch())

HTML:

<button onclick="getUser()">Get User Info</button><div id="userInfo"></div>

JavaScript:

function getUser() {  fetch("user.php?id=1")    .then(response => response.json())    .then(data => {      document.getElementById("userInfo").innerHTML =        "Name: " + data.name + "<br>Email: " + data.email;    });}

PHP (user.php):

<?php$user = ['name' => 'Alice', 'email' => 'alice@example.com'];echo json_encode($user);?>

? Example 3: Handling Error Responses

fetch("missing-file.php")  .then(response => {    if (!response.ok) {      throw new Error("HTTP Error: " + response.status);    }    return response.text();  })  .then(data => {    console.log("Success:", data);  })  .catch(error => {    console.error("Error:", error.message);  });

? Using AJAX Response with XMLHttpRequest

const xhr = new XMLHttpRequest();xhr.open("GET", "data.json", true);xhr.onload = function () {  if (xhr.status === 200) {    const data = JSON.parse(xhr.responseText);    console.log("Name:", data.name);  }};xhr.send();

? Summary

  • AJAX responses can be text, HTML, JSON, or XML.

  • Use .text() or .json() methods with fetch() to process them.

  • You can dynamically update your webpage based on the response data.

  • Always check for errors to handle failed responses gracefully.


Would you like to see an example of using an AJAX response to populate a table or dropdown dynamically?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql