Skip to content

AJAX XML

PHP Example - AJAX with Server Data (JSON)

Section titled “PHP Example - AJAX with Server Data (JSON)”

AJAX (Asynchronous JavaScript and XML) allows web pages to update content dynamically by exchanging data with a server behind the scenes, without requiring a full page reload. While originally associated with XML, JSON (JavaScript Object Notation) is now the predominant data format for AJAX communication due to its simplicity and direct mapping to JavaScript objects.

This example demonstrates how a web page can use JavaScript’s fetch API to request data from a PHP script, which in turn reads information (originally from an XML file, but served as JSON) and sends it back to the page.

Imagine a dropdown list of artists. Selecting an artist triggers an AJAX request to a PHP script, which looks up CD details for that artist (from a data source like cd_catalog.xml) and returns the information as JSON. The JavaScript then displays this information on the page.

<!-- Placeholder for a simulated live example -->
<div style="border: 1px solid #ccc; padding: 15px; margin-bottom: 15px;">
<form id="cdForm">
<label for="cdSelect">Select a CD Artist:</label>
<select name="cds" id="cdSelect">
<option value="">Select an Artist...</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint" style="margin-top: 15px; padding-top: 10px; border-top: 1px dashed #eee;">
**CD info will be listed here...**
</div>
</div>
<script>
// Modern JavaScript using fetch API
document.getElementById('cdSelect').addEventListener('change', function() {
showCD(this.value);
});
async function showCD(artistName) {
const hintElement = document.getElementById("txtHint");
if (artistName === "") {
hintElement.innerHTML = "**CD info will be listed here...**";
return;
}
hintElement.innerHTML = "<i>Loading...</i>"; // Provide user feedback
try {
// Construct the URL for the PHP script, passing the artist name as a query parameter
const url = `get_cd_data.php?artist=${encodeURIComponent(artistName)}`;
const response = await fetch(url);
if (!response.ok) {
// Handle HTTP errors (e.g., 404 Not Found, 500 Server Error)
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Expecting JSON data from the PHP script
const data = await response.json();
if (data.error) {
// Handle application-specific errors returned by PHP
hintElement.innerHTML = `<span style='color: red;'>Error: ${data.error}</span>`;
} else if (data.title) {
// Display the received CD data
hintElement.innerHTML =
`**Title:** ${data.title}<br>` +
`**Artist:** ${data.artist}<br>` +
`**Country:** ${data.country}<br>` +
`**Company:** ${data.company}<br>` +
`**Price:** ${data.price}<br>` +
`**Year:** ${data.year}`;
} else {
hintElement.innerHTML = "<i>No CD found for this artist.</i>";
}
} catch (error) {
// Handle network errors or parsing errors
console.error('Fetch error:', error);
hintElement.innerHTML = `<span style='color: red;'>Failed to fetch CD data. ${error.message}</span>`;
}
}
</script>

Example Explained - The HTML & JavaScript (Client-Side)

Section titled “Example Explained - The HTML & JavaScript (Client-Side)”

The HTML sets up a simple form with a dropdown (<select>). An event listener is attached to this dropdown using JavaScript.

<form id="cdForm">
<label for="cdSelect">Select a CD Artist:</label>
<select name="cds" id="cdSelect">
<option value="">Select an Artist...</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint" style="margin-top: 10px;">
**CD info will be listed here...**
</div>

When the user changes the selected option:

  1. An event listener triggers the showCD() function, passing the selected artist’s name.
  2. The showCD() function (using async/await for cleaner asynchronous code):
  3. Checks if an artist is selected. If not, it resets the display area (txtHint).
  4. Displays a “Loading…” message for better user experience.
  5. Uses the fetch() API to send an asynchronous GET request to get_cd_data.php.
  6. The artist’s name is URL-encoded and appended as a query parameter (?artist=...).
  7. Checks if the HTTP response status is OK (e.g., 200). Throws an error if not.
  8. Parses the response body as JSON using response.json().
  9. Checks the parsed JSON data for application errors or valid CD info.
  10. Updates the txtHint element’s HTML with the received data (or an error message).
  11. Includes try...catch to handle potential network errors or JSON parsing issues.
document.getElementById('cdSelect').addEventListener('change', function() {
showCD(this.value);
});
async function showCD(artistName) {
const hintElement = document.getElementById("txtHint");
if (artistName === "") { /* ... reset ... */ return; }
hintElement.innerHTML = "<i>Loading...</i>";
try {
const response = await fetch(`get_cd_data.php?artist=${encodeURIComponent(artistName)}`);
if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); }
const data = await response.json();
if (data.error) {
hintElement.innerHTML = `<span style='color: red;'>Error: ${data.error}</span>`;
} else if (data.title) {
// ... display CD info from data object ...
hintElement.innerHTML = `**Title:** ${data.title} ...`;
} else {
hintElement.innerHTML = "<i>No CD found.</i>";
}
} catch (error) {
console.error('Fetch error:', error);
hintElement.innerHTML = `<span style='color: red;'>Failed to fetch data.</span>`;
}
}

The PHP File (get_cd_data.php - Server-Side)

Section titled “The PHP File (get_cd_data.php - Server-Side)”

This PHP script runs on the server. It receives the artist name requested by the JavaScript, finds the corresponding CD data (in this example, by parsing an XML file), and sends the data back as a JSON response.

Data Source (cd_catalog.xml - Assumed Structure):

Section titled “Data Source (cd_catalog.xml - Assumed Structure):”
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Still Waters</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<!-- ... more CD entries ... -->
</CATALOG>
  1. Set the Content-Type header to application/json to inform the client that JSON data is being returned.
  2. Retrieve the artist name from the $_GET['artist'] query parameter. Sanitize or validate this input if necessary in a real application.
  3. Define the path to the XML data file.
  4. Use libxml error handling and disable external entities for security.
  5. Load the XML file using simplexml_load_file(). Handle potential loading errors.
  6. Use XPath ($xml->xpath(...)) to efficiently search for the CD element(s) matching the requested artist. XPath is generally much more efficient than manually looping through all elements.
  7. If a matching CD is found:
  8. Extract the required data (title, artist, country, etc.) from the SimpleXMLElement.
  9. Create a PHP associative array containing the CD data.
  10. If no match is found or an error occurs:
  11. Create an associative array containing an error message.
  12. Use json_encode() to convert the PHP array into a JSON string.
  13. Echo the JSON string as the response body.
<?php
// Set header to indicate JSON response
header('Content-Type: application/json');
// Get the artist parameter from the request
$requested_artist = isset($_GET['artist']) ? trim($_GET['artist']) : '';
$xmlFile = 'cd_catalog.xml'; // Path to your XML file
$response_data = []; // Initialize response array
if (empty($requested_artist)) {
$response_data['error'] = 'No artist specified.';
} elseif (!file_exists($xmlFile)) {
$response_data['error'] = 'Data source not found.';
} else {
// Enable libxml error handling & disable external entities (security)
libxml_use_internal_errors(true);
libxml_disable_entity_loader(true);
$xml = simplexml_load_file($xmlFile);
if ($xml === false) {
$response_data['error'] = 'Failed to parse XML data.';
// Optionally log libxml_get_errors() here for debugging
libxml_clear_errors();
} else {
// Use XPath to find the CD by artist
// Note: XPath injection is possible if $requested_artist is not handled carefully.
// In a real app, validate/sanitize $requested_artist before using in XPath.
// Using prepared statements is generally safer if querying a database.
$query = sprintf("//CD[ARTIST='%s']", addslashes($requested_artist)); // Basic escaping for XPath
$results = $xml->xpath($query);
if ($results && count($results) > 0) {
// Found at least one match, take the first one
$cd = $results[0];
$response_data = [
'title' => (string)$cd->TITLE, // Cast SimpleXMLElements to string
'artist' => (string)$cd->ARTIST,
'country' => (string)$cd->COUNTRY,
'company' => (string)$cd->COMPANY,
'price' => (string)$cd->PRICE,
'year' => (string)$cd->YEAR
];
} else {
// No CD found for this artist
$response_data['message'] = 'No CD found for this artist.';
// No error, just no data found
}
}
}
// Encode the response array as JSON and output it
echo json_encode($response_data);
?>

This updated approach uses modern JavaScript (fetch, async/await), communicates using the standard JSON format, and employs more efficient XML parsing (XPath) on the server-side, reflecting current web development practices.