I’m working on a web project where I need to send data from an HTML file to a PHP file using fetch. My project structure is as follows:
Football-Manager-Analysis/
├── templates/
│ └── index.html
├── importData.PHP
├── app.py
My index.html
contains the following JavaScript code to send data to importData.PHP
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scouting and Transfer Market Analysis Tool</title>
</head>
<body>
<div class="container">
<h1>Scouting and Transfer Market Analysis Tool</h1>
<input type="file" id="fileInput" accept=".html">
<div class="buttons">
<button onclick="loadFile()">Load Data</button>
<button onclick="runData()">Run Data</button>
</div>
<div id="tableContainer"></div>
</div>
<script>
function loadFile() {
const input = document.getElementById('fileInput');
const file = input.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const parser = new DOMParser();
const doc = parser.parseFromString(e.target.result, 'text/html');
const table = doc.querySelector('table');
document.getElementById('tableContainer').innerHTML = table.outerHTML;
};
if (file) {
reader.readAsText(file);
} else {
alert('Please select a file.');
}
}
function runData() {
const table = document.querySelector('#tableContainer table');
if (!table) {
alert('No data loaded. Please load data first.');
return;
}
const data = extractTableData(table);
sendDataToServer(data);
}
function extractTableData(table) {
const rows = table.querySelectorAll('tr');
const data = [];
rows.forEach(row => {
const cells = row.querySelectorAll('th, td');
const rowData = [];
cells.forEach(cell => {
rowData.push(cell.textContent);
});
data.push(rowData);
});
return data;
}
function sendDataToServer(data) {
fetch('../importData.PHP', { // Adjusted to use a relative path
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ tableData: data })
})
.then(response => response.json())
.then(result => {
alert('Data successfully sent to the server');
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while sending data to the server');
});
}
</script>
</body>
</html>
However, when I try to send the data, I get a 404 error:
127.0.0.1 - - [22/May/2024 00:14:37] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [22/May/2024 00:14:42] "POST /importData.PHP HTTP/1.1" 404 -
I’m running my server from the Football-Manager-Analysis directory. The PHP file is located in the root directory of the project, one level up from the templates folder where index.html is located.
I’ve verified the file’s existence and permissions, and I’m using a relative path. What could be causing this 404 error, and how can I resolve it?
Face of Coding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.