I’m currently working on a web application where I fetch data from a PHP script (candidate_record.php) to populate an HTML table with candidate information. The PHP script retrieves data from a MySQL database and outputs it as JSON. However, I’m encountering issues with parsing this JSON data correctly in my JavaScript code to populate the table.
Here is the summary
- PHP Script (candidate_record.php): Retrieves candidate data from MySQL database and outputs JSON.
- JavaScript in HTML (candidate_record.html): Fetches JSON data from PHP script using fetch(), parses it using response.json(), and then attempts to populate an HTML table dynamically with this data.
PHP (candidate_record.php):
<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');
include 'db_connection.php';
// Retrieve candidates from database
$sql = "SELECT * FROM candidate";
$result = mysqli_query($conn, $sql);
if ($result) {
// Fetch all rows from the result set
$candidates = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($candidates);
} else {
echo json_encode(["error" => "Error retrieving candidates: " . mysqli_error($conn)]);
}
// Close connection
mysqli_close($conn);
JavaScript in HTML (candidate_record.html):
function fetchCandidates() {
fetch('candidate_record.php')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Check for errors in response
if (data.error) {
throw new Error(data.error);
}
console.log('Fetched candidates:', data); // Log fetched data
// Populate candidates table with fetched data
populateCandidatesTable(data);
})
.catch(error => {
console.error('Error fetching candidates:', error);
// Handle error display if necessary
});
}
I attempted to fetch JSON data from a PHP script (candidate_record.php) using JavaScript’s fetch() API. The PHP script retrieves candidate data from a MySQL database and outputs it as JSON. Upon fetching the data in my JavaScript code, I used response.json() to parse the JSON data and then dynamically populate an HTML table () with this data.
I expected the JSON data fetched from the PHP script to be successfully parsed and used to populate the HTML table with candidate information. The table should display rows containing each candidate’s ID, name, party affiliation, and other relevant details fetched from the database. Instead of successfully populating the HTML table, I encountered a SyntaxError: Unexpected token ‘C’ when attempting to parse the JSON response in JavaScript. This error suggests an issue with how the JSON data is being processed or formatted during the fetch operation.
Justin Ramos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.