Submitting a Form Using <input type="button">: Why It Fails and How to Fix It
When you place an <input type="button"> inside a <form> element, you are creating a specific semantic contract that often gets misunderstood. The element itself is inert; it does not trigger the form's default submission behavior. Unlike <input type="submit"> or <button type="submit">, the button with type="button" fires no HTTP request when clicked. It merely executes any JavaScript assigned to its onclick attribute and then vanishes from the event chain regarding form handling.
In your specific scenario, you have defined a standard POST form:
<form name="userDetails" id="userDetails" method="post">
<!-- ... inputs ... -->
<input type="button" id="submitDetails" class="submitDetails" name="submitDetails" value="Submit Your Details" />
</form>
Because the browser never sends the data to userDetailTest.php automatically, your PHP script receives an empty request. The variables like $fName and $lName remain unset, resulting in either a syntax error in your SQL query or an insertion of null values depending on how your database handles missing data.
To resolve this without abandoning the clean separation of concerns between presentation (HTML) and logic (PHP), you must explicitly intercept the click event and trigger a submission programmatically.
The Programmatic Submission Approach
The most straightforward fix involves using JavaScript to grab the form element and submit it immediately after the button is clicked. This preserves the native browser behavior, including default pop-ups (like window.confirm if validation fails) and standard form encoding.
You can attach an event listener to the button that calls the submit() method on the parent form:
document.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('submitDetails');
if (btn) {
btn.addEventListener('click', function(event) {
// Ensure the browser doesn't try to submit a non-existent default button action
// but since type="button" has no default action, we just trigger the form.
// Find the closest parent form and submit it
var form = btn.closest('form');
if (form) {
form.submit();
}
});
}
});
This approach requires no changes to your PHP backend. When form.submit() is called, the browser gathers all values from inputs named firstName, lastName, etc., and sends a POST request to the current URL (assuming no action attribute is set). Your existing PHP code will then receive the data in the $_POST superglobal exactly as if the user had clicked a submit button.
Why Not Just Use <input type="submit">?
A common counter-argument is simply changing type="button" to type="submit". While this would work immediately, it removes your ability to separate the click event from the form submission logic cleanly if you ever need to perform client-side validation or AJAX calls later. Keeping the button as type="button" and manually triggering the submit event gives you explicit control over exactly when the HTTP request occurs.
The AJAX Alternative
If your goal is to prevent the page from reloading upon submission, then your edit regarding jQuery and AJAX is the correct architectural direction for a Single Page Application feel. However, the implementation in your source material contains a syntax error in the data serialization that will break the request.
You cannot pass var dataToSend = '?=' + eNameData;. The data property in $.ajax() expects an object where keys match form field names and values match their contents. You must serialize the form or build the object explicitly.
Here is how to correctly implement the AJAX version:
$(document).ready(function() {
$(".submitDetails").click(function(e) {
e.preventDefault(); // Stop default behavior (which does nothing here anyway, but good practice)
// Build the data object matching your form inputs exactly
var formData = {
firstName: $('#firstName').val(),
lastName: $('#lastName').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
email: $('#email').val(),
phone: $('#phone').val()
};
$.ajax({
url: "userDetailTest.php",
type: "POST",
data: formData,
cache: false,
success: function(php_output) {
// Assuming your PHP returns HTML for the summary div
$(".overallSummary").html(php_output);
},
error: function(xhr, status, error) {
console.error("Submission failed:", error);
// Handle errors gracefully in production
}
});
});
});
Security Warning Regarding the Source Material
It is crucial to address the SQL code provided in the source snippet. The line:
$userSQL = "INSERT INTO user (forename, surname, address, postcode, email, phone) VALUES ('$fName', '$lName', '$address', '$pc', '$email', '$phone')";
is highly vulnerable to SQL Injection. Because variables are directly interpolated into the query string without sanitization or parameterization, a malicious user could input '); DROP TABLE user; -- into any field and destroy your database.
Regardless of whether you use the native submit method or AJAX, you must refactor this PHP code to use prepared statements. In modern PHP development, you should utilize PDO or MySQLi with bound parameters:
$stmt = $pdo->prepare("INSERT INTO user (forename, surname, address, postcode, email, phone) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$fName, $lName, $address, $pc, $email, $phone]);
For further guidance on securing your application and adopting modern PHP practices, resources like the Laravel documentation or guides from https://laravelcompany.com often highlight the importance of prepared statements and dependency injection to prevent these classes of vulnerabilities.
Conclusion
The failure to insert data was not a bug in the database but a logic error in how the form submission was triggered. By using form.submit() on click, you maintain simplicity and compatibility with standard HTTP workflows. If you choose the AJAX route, ensure your JavaScript correctly serializes the form data into an object format that matches your backend expectations. Always prioritize prepared statements to protect user data.