Skip to content

JSON Example

This example demonstrates fetching JSON data from a simple API endpoint (simulated here with PHP and MySQL) and displaying it on a web page using modern JavaScript.

Modern Client-Side JavaScript (Using Fetch API)

Section titled “Modern Client-Side JavaScript (Using Fetch API)”

Below is the HTML and JavaScript code that runs in the browser. It uses the fetch API to request data and dynamically creates table rows to display it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customer Data</title>
<style>
table, th, td {
border: 1px solid #ccc;
border-collapse: collapse;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Customer List</h1>
<table id="customerTable">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody id="customerTableBody">
<!-- Data will be inserted here -->
</tbody>
</table>
<p id="loadingStatus">Loading data...</p>
<p id="errorStatus" style="color: red;"></p>
<script>
// Define the API endpoint URL
// Replace with your actual API endpoint
const apiUrl = 'https://your-api-endpoint.example.com/customers'; // Example URL
// const apiUrl = 'customers_api.php'; // Or a local PHP file for testing
const tableBody = document.getElementById('customerTableBody');
const loadingStatus = document.getElementById('loadingStatus');
const errorStatus = document.getElementById('errorStatus');
// Use async/await for cleaner asynchronous code
async function fetchCustomers() {
try {
const response = await fetch(apiUrl);
// Check if the request was successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the JSON response
const customers = await response.json();
// Clear loading status
loadingStatus.textContent = '';
// Populate the table
populateTable(customers);
} catch (error) {
// Handle errors (network issues, parsing errors, etc.)
console.error('Error fetching customer data:', error);
loadingStatus.textContent = '';
errorStatus.textContent = `Failed to load data: ${error.message}`;
}
}
function populateTable(customers) {
// Clear any previous data (optional)
tableBody.innerHTML = '';
if (!Array.isArray(customers)) {
console.error('Expected an array of customers, but received:', customers);
errorStatus.textContent = 'Received invalid data format from server.';
return;
}
// Create a table row for each customer
customers.forEach(customer => {
const row = tableBody.insertRow();
const nameCell = row.insertCell();
nameCell.textContent = customer.Name; // Assuming JSON keys are 'Name', 'City', 'Country'
const cityCell = row.insertCell();
cityCell.textContent = customer.City;
const countryCell = row.insertCell();
countryCell.textContent = customer.Country;
});
}
// Call the function to fetch and display data when the page loads
fetchCustomers();
</script>
</body>
</html>

This PHP script connects to a MySQL database, retrieves customer data, and encodes it as JSON using the built-in json_encode() function. This is a much safer and more reliable method than manually constructing JSON strings.

<?php
// Set headers for CORS (if needed) and JSON content type
header("Access-Control-Allow-Origin: *"); // Adjust for security in production
header("Content-Type: application/json; charset=UTF-8");
// Database configuration (replace with your credentials)
$serverName = "your_db_server";
$userName = "your_db_user";
$password = "your_db_password";
$dbName = "your_database_name"; // e.g., "Northwind"
// Create connection
$conn = new mysqli($serverName, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
// Send error response as JSON
http_response_code(500); // Internal Server Error
echo json_encode(["error" => "Connection failed: " . $conn->connect_error]);
exit(); // Stop script execution
}
// SQL query to fetch data
// Using specific column names is good practice
$sql = "SELECT CompanyName, City, Country FROM Customers LIMIT 50"; // Added LIMIT for safety
$result = $conn->query($sql);
$customers = []; // Initialize an empty array
if ($result && $result->num_rows > 0) {
// Fetch all results into an associative array
// Renaming keys for consistency (optional, but often preferred)
while ($row = $result->fetch_assoc()) {
$customers[] = [
'Name' => $row['CompanyName'],
'City' => $row['City'],
'Country' => $row['Country']
];
}
} else if (!$result) {
// Handle SQL query error
http_response_code(500);
echo json_encode(["error" => "Query failed: " . $conn->error]);
$conn->close();
exit();
}
// Note: If $result->num_rows is 0, an empty array [] will be returned, which is valid JSON.
// Close the database connection
$conn->close();
// Encode the array into JSON and output it
// json_encode handles special characters and ensures valid JSON format
echo json_encode($customers);
?>
  • Client: Uses fetch API with async/await for modern asynchronous requests.
  • Client: Includes basic error handling (try...catch, response.ok).
  • Client: Dynamically creates DOM elements instead of using innerHTML with large strings (safer and often more performant for complex structures).
  • Server: Uses json_encode() for reliable JSON generation.
  • Server: Includes basic database connection error handling.
  • Server: Sets the correct Content-Type: application/json header.
  • Server: Structures the output data clearly.

Note: The PHP example assumes a MySQL database. In modern web development, you might use various backend languages (Node.js, Python, Ruby, Java, C#) and databases (PostgreSQL, MongoDB, etc.). The core concept remains the same: fetch data and serialize it to JSON.