Trouble Parsing JSON Data from PHP Script to Populate HTML Table

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):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?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);
</code>
<code><?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); </code>
<?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):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
});
}
</code>
<code>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 }); } </code>
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.

New contributor

Justin Ramos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật