PHP Submit on Select
The goal is to eliminate a visible "Submit" button and trigger a form submission immediately when the user selects a value from a dropdown. In raw HTML, there is no event attribute that automatically dispatches a POST request upon change. To achieve this behavior without JavaScript libraries or complex event listeners, you must leverage the native <form> element's onsubmit attribute combined with an immediate default action.
The core mechanism relies on moving the control out of the user's hand before it is released. When a user clicks outside the form or presses Enter while focused on an input, the browser processes the submission. If the form contains only one selectable option that isn't the initial placeholder, you can set the onsubmit attribute to execute the action immediately upon any change event.
However, there are significant caveats regarding how browsers handle this pattern. Most modern browsers will prevent the form from submitting if the selection is cleared or reset before the user leaves the field. To make this work reliably, you need to ensure the form has a single active state at all times. The solution involves using the onsubmit attribute directly on the <form> tag and preventing the default submission behavior within an inline script only when necessary (like resetting the select), or allowing the natural flow if the selection is final.
In your specific case, you are loading options from a database using deprecated mysql_* functions. Before implementing the automatic submit logic, you must address the security and compatibility risks of those functions. The mysql_query extension has been removed in PHP 7.0 and later, meaning this code will fail on any modern server environment. You should migrate to either MySQLi or PDO immediately. If you remain on legacy systems, use mysqli_select() or prepare statements to prevent SQL injection.
Here is how you can structure the form to submit automatically when a value other than -1 is selected:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return handleSubmission(this);">
<table class="form">
<select name="category" class="formfield" id="category">
<option value="-1">Category</option>
<?php
// Use mysqli instead of mysql for PHP 7+ compatibility
$mysqli = new mysqli("localhost", "user", "pass", "database");
// Prevent SQL injection by using prepared statements
$stmt = $mysqli->prepare("SELECT category FROM category");
$stmt->execute();
$result = $stmt->get_result();
while ($row_c = $result->fetch_assoc()) {
// Check if this is the default option to avoid submitting on load
if ($row_c['category'] != '-1') {
echo '<option value="'.$row_c['category'].'">';
echo htmlspecialchars($row_c['category']);
echo '</option>';
}
}
?>
</select>
</table>
</form>
The onsubmit handler allows you to intercept the submission. A common pattern involves checking if a valid category was selected before proceeding. If the user selects a value and clicks away, the form submits. However, if you want to prevent the initial load from triggering a submit (which happens if the first option is treated as "selected"), you must ensure the value attribute of the <select> element does not match any valid database entry initially.
The provided code snippet above checks if the current value is -1. If it is, and the user changes it to a real category ID, the form should submit. The trade-off here is that the form will submit even if the user simply clicks outside the select box after making a choice. This can feel abrupt to users who expect a button press or an explicit enter key action.
To mitigate this frustration without adding JavaScript complexity, you can rely on the fact that most users naturally press Enter when they finish typing or selecting. If automatic submission causes data loss (e.g., if the user selects "Category A", then changes their mind to "Category B" before submitting), this pattern is unsuitable for your use case.
If you are using Laravel, the framework provides robust form helpers that manage these interactions more elegantly via AJAX or standard Blade directives. You can generate similar forms using Form::select() and handle the submission logic in your controller or route without relying on raw HTML attributes. For instance, a route might look like:
Route::post('/category-save', function ($request) {
$categoryId = $request->input('category');
// Process logic here
});
Ultimately, automatic submission works best for single-purpose forms where the user's intent is clear and immediate. If your application requires confirmation or complex validation before saving, forcing a submit on change will degrade the user experience. Always prioritize explicit actions over implicit ones unless you are certain of the context.