XML AJAX database interaction with a simple example:
Suppose you have a web application that displays a list of books stored in a database. You want to use XML AJAX techniques to fetch this data from the server and display it dynamically on a web page without reloading the entire page.
XML (eXtensible Markup Language): Used to structure and exchange data between the server and the client browser.
AJAX (Asynchronous JavaScript and XML): Allows the client browser to make asynchronous requests to the server, fetch data, and update the web page dynamically without reloading.
Database: Stores the book data, which can be queried and fetched by the server.
index.html
):Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book List</title> <script src="script.js" defer></script> </head> <body> <h2>Book List</h2> <button id="fetchButton">Fetch Books</button> <div id="bookList"></div> </body> </html>
script.js
):Example
document.getElementById('fetchButton').addEventListener('click', fetchBooks); function fetchBooks() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; displayBooks(xmlDoc); } }; xhttp.open('GET', 'fetchBooks.php', true); xhttp.send(); } function displayBooks(xmlDoc) { var bookListDiv = document.getElementById('bookList'); bookListDiv.innerHTML = ''; var books = xmlDoc.getElementsByTagName('book'); for (var i = 0; i < books.length; i++) { var title = books[i].getElementsByTagName('title')[0].textContent; var author = books[i].getElementsByTagName('author')[0].textContent; var year = books[i].getElementsByTagName('year')[0].textContent; var bookInfo = 'Title: ' + title + ''; bookInfo += 'Author: ' + author + ''; bookInfo += 'Year: ' + year + ''; bookInfo += ''; bookListDiv.innerHTML += bookInfo; } }
fetchBooks.php
):Example
connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to fetch books from database $sql = "SELECT * FROM books"; $result = $conn->query($sql); // Output XML header('Content-Type: text/xml'); echo ''; echo ''; if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo ' '; $conn->close(); ?>'; echo ' '; } } echo '' . $row['title'] . ' '; echo '' . $row['author'] . ' '; echo '' . $row['year'] . ' '; echo '
fetchBooks()
function is called.fetchBooks.php
script on the server.This example demonstrates how XML AJAX techniques can be used to fetch data from a database and display it dynamically on a web page without reloading the entire page