Reputation: 9
I have a html form and php file as its action. When I click submit button it runs the php code but also load a blank page and the url changes.
How can I make just run code and stay on the same html page?
Upvotes: 0
Views: 701
Reputation: 4889
It sounds like you may need to develop beyond the "one page = one script" paradigm. Now, there are a number of possible approaches to "not leaving the page", such as:
Include your form processing code in the form page itself. Pros: Really simple and rudimentary. Cons: Code not reusable.
Submit the form via javascript (AJAX/Fetch). Pros: "Modern" and elegant when properly done. Cons: Relatively complicated. Requires both PHP and Javascript.
The simplest "elegant" approach: Separate your form-processing logic and include/call from the page when a form is submitted. Basic example:
<?php /* form.php */
if(!empty($_POST)) { // if form was submitted ("post")
include 'form_processor.php';
$result = process_form($_POST);
echo 'Form Process Result: ' . $result;
}
?>
<form action="form.php" method="post">
... your HTML form here ...
</form>
<?php /* form_processor.php */
function process_form($post, $args = []) {
$errors = [];
// do stuff with the post data: validate, store, etc.
if(count($errors) > 0) {
$result = 'Errors: ' . implode(', ', $errors);
} else {
$result = 'Okay';
}
return $result;
}
You will need to put some thought into crafting a form processor that's reusable in multiple contexts, e.g. by passing arguments that define case-specific validation and data processing. Probably turn it into a class, or at least into multiple functions with clear separation of tasks (validating, storing, e-mailing, etc.). The above should give you a basic path forward.
Upvotes: 1