Skip to content

AJAX XML

What is PHP?

PHP is a server-side scripting language that is used to create dynamic web pages. It is an open-source language that can be embedded in HTML code. PHP is popular because it is easy to learn, and it allows web developers to create interactive and dynamic web pages quickly.

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique that allows web developers to update parts of a web page without refreshing the entire page. It is commonly used in web applications to improve user experience and reduce server load.

What is XML?

XML (Extensible Markup Language) is a markup language used to store and transport data. XML is often used in conjunction with AJAX and PHP to create dynamic content. XML is human-readable, which makes it easy to understand and work with.

Why Use PHP, AJAX, and XML Together?

Combining PHP, AJAX, and XML enables developers to build responsive web applications that update specific content dynamically. This approach improves user experience by eliminating full page reloads while reducing server load.

How to Use PHP, AJAX, and XML Together

To use PHP, AJAX, and XML together, you will need to follow these steps:

  1. Create a PHP script that retrieves data from a database or file.
  2. Use AJAX to call the PHP script and retrieve the data.
  3. Parse the XML response in JavaScript, convert it to HTML elements, and display it on the web page.

Step 1: Create a PHP Script

The first step is to create a PHP script that retrieves data from a database or file. This script will be responsible for retrieving the data that will be displayed on the web page.

Here is an example of a PHP script that retrieves data from a database:

Example of a PHP script that retrieves data from a database

php
<?php
// Connect to database
$con = mysqli_connect("localhost","username","password","database");

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

// Retrieve data from database
// Note: Ensure the database contains a table named 'table' with columns: title, description, price
// Note: In production, use prepared statements to prevent SQL injection
$result = mysqli_query($con,"SELECT * FROM table");

// Set content type to XML
header('Content-Type: text/xml');
echo '<?xml version="1.0"?>';
echo '<items>';

// Loop through the results and add them to XML
while($row = mysqli_fetch_array($result)) {
    echo '<item>';
    echo '<title>' . htmlspecialchars($row['title']) . '</title>';
    echo '<description>' . htmlspecialchars($row['description']) . '</description>';
    echo '<price>' . htmlspecialchars($row['price']) . '</price>';
    echo '</item>';
}

echo '</items>';
?>

Note: In production, replace hardcoded credentials with environment variables and add error handling for database connections.

Step 2: Use AJAX to Call the PHP Script

The next step is to use AJAX to call the PHP script and retrieve the data. First, ensure your HTML page contains a container element where the fetched data will be injected:

html
<div id="data-container"></div>

Here is an example of an AJAX script that calls the PHP script created in step 1:

Example of using AJAX to call a PHP script and retrieve the data

javascript
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
        if (this.status == 200) {
            var xmlDoc = this.responseXML;
            var items = xmlDoc.getElementsByTagName("item");
            var container = document.getElementById("data-container");
            container.innerHTML = ""; // Clear previous data

            for (var i = 0; i < items.length; i++) {
                var title = items[i].getElementsByTagName("title")[0].textContent;
                var desc = items[i].getElementsByTagName("description")[0].textContent;
                var price = items[i].getElementsByTagName("price")[0].textContent;

                var div = document.createElement("div");
                div.className = "item";
                div.innerHTML = "<h3>" + title + "</h3><p>" + desc + "</p><span>" + price + "</span>";
                container.appendChild(div);
            }
        } else {
            console.error("Request failed with status: " + this.status);
            var container = document.getElementById("data-container");
            container.innerHTML = "<p>Error loading data.</p>";
        }
    }
};
xmlhttp.open("GET", "getdata.php", true);
xmlhttp.send();

Note: Ensure the PHP script outputs no whitespace or BOM before the XML declaration, as this will cause this.responseXML to return null. If needed, add ob_clean(); at the start of the PHP file. If your PHP script is hosted on a different domain, ensure the server sends appropriate CORS headers (e.g., Access-Control-Allow-Origin: *).

Step 3: Format the Data and Display it on the Web Page

Once the data is retrieved, we need to parse the XML response and convert it into HTML elements that the browser can render. In this step, we will use JavaScript to read the XML structure and inject it into the page. The XML format itself looks like this:

Example of formatting and displaying XML data

xml
<items>
    <item>
        <title>Item 1</title>
        <description>This is the description of item 1.</description>
        <price>$10.00</price>
    </item>
    <item>
        <title>Item 2</title>
        <description>This is the description of item 2.</description>
        <price>$20.00</price>
    </item>
    <item>
        <title>Item 3</title>
        <description>This is the description of item 3.</description>
        <price>$30.00</price>
    </item>
</items>

After parsing, the JavaScript creates standard HTML elements (like <div>, <h3>, and <span>) which can then be styled with CSS. Here is an example of CSS that matches the generated HTML structure:

Example CSS for styling the rendered data

css
.item {
    border: 1px solid #ccc;
    padding: 10px;
    margin: 10px 0;
    border-radius: 4px;
}
.item h3 { margin: 0 0 5px; }
.item span { color: #2a9d8f; font-weight: bold; }

Conclusion

Using PHP, AJAX, and XML together enables developers to build dynamic web pages that update specific content without full reloads. By following the steps above, you can implement this pattern to improve user experience and reduce server load.

Note: While this tutorial uses XML and XMLHttpRequest for educational purposes, modern web applications typically prefer JSON and the fetch API for AJAX data exchange due to native JavaScript support and simpler syntax.

If you have any questions or need further assistance, feel free to reach out to us.

Practice

What is the correct way to return an XMLHttpRequest object in PHP using AJAX XML?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.