Why HTML Buttons Don't Render After PHP Headers Are Sent
When you encounter an issue where HTML elements like buttons fail to display immediately after executing database operations in a .php file, the culprit is almost always the HTTP response lifecycle. In your specific case, the code sends data headers before any HTML content is generated. Once header() is called, the server considers the response headers "sent." At that exact moment, you lose the ability to inject HTML into the output buffer because the stream is effectively locked for text or binary data, not mixed with headers in unexpected ways, but more critically, the logic flow prevents subsequent echo statements from rendering correctly if the script terminates or behaves unexpectedly.
Looking closely at your implementation:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// ... database logic ...
if(mysqli_query($conn, $sql)){
echo "New record created successfully!";
// ... more echo statements ...
} else {
echo "Error 1: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
The critical error lies in the Content-Type header. You have explicitly set the response to application/json. When a browser receives this header, it expects a JSON payload (like {"message": "Success"}), not raw HTML text containing buttons and divs. Even if the script continues running and tries to echo <div>...</div>, the browser will likely ignore that content or treat it as invalid for the declared JSON type.
Furthermore, mixing echo statements with database queries without proper output buffering control can lead to unpredictable behavior. If you intend to return HTML after a successful insert, you must change your Content-Type header to text/html. However, a more robust architectural pattern is to separate the data processing from the view rendering entirely.
The Header Lock and Content-Type Mismatch
The most immediate fix for your current code is to align your headers with your output. If you want to show a success message and a button inside an HTML page, declare text/html:
<?php
$user = 'root';
$pass = '';
$db = 'testdb';
// Change this line to match your intended output format
header("Content-Type: text/html; charset=UTF-8");
$conn = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect.");
$sql = "INSERT INTO Customers (CompanyName, City, Country) VALUES (?, ?, ?);"; // Use prepared statements for security
$stmt = $conn->prepare($sql);
// Bind parameters here...
$stmt->execute();
if ($stmt){
echo "<div id='center_button'>";
echo "<button onclick=\"location.href='index.html'\">Back to Home</button>";
echo "</div>";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
?>
By switching to text/html, the browser understands that the response body can contain HTML tags. Without this change, the access-control header combined with a JSON content type creates an environment where standard HTML rendering is suppressed or misinterpreted by the client.
Output Buffering and Script Flow
Another subtle issue in your original snippet is the placement of the button outside the conditional block but inside the file. While PHP allows you to echo HTML anywhere, relying on it after database operations can be fragile. If the script were to terminate early due to an error or if output buffering isn't managed correctly, the HTML might not flush properly.
A better approach is to wrap your logic in functions or use template engines that handle the separation of concerns. This ensures that the database query results are passed to a view layer where the HTML structure (like your #center_button div) is defined once and rendered cleanly.
Security Consideration
Your current SQL query uses direct interpolation ($_POST[...]) which is vulnerable to SQL injection attacks. In a production environment, you must use prepared statements as shown in the corrected example above. Never trust user input directly into your query string.
If you are looking for a framework-based solution that handles this separation of logic and view automatically without writing raw PHP and HTML mixed together, exploring modern stacks like Laravel can be beneficial. Platforms such as https://laravelcompany.com offer resources on building robust applications where controllers handle data and views handle the HTML, preventing exactly the kind of header/output conflicts you are experiencing.
