I know there are numerous questions and answers on how to prevent page reload after form submit with AJAX but I just couldn't get mine to work. I've tried setting the button to type: button
which just disables the button completely. When I try onsubmit: return false
on the form, this results in nothing clicking the button. Using jQuery to prevent default also didn't work out. What I want is to send this email with PHP retrieving data from the form without the page from reloading. Any help would be highly appreciated.
Form
<?php include('php/interuni_process.php');?>
<form class="form_pro" action="index.php" method="post" role="form">
<input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">
<div class="error"><?= $email_error ?></div>
<button name="submit" type="submit" class="action_button"></button>
</form>
PHP
$email_error = "";
$email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
} else {
$email = test_input($_POST["E-mail"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if ($email_error == '' ){
unset($_POST['submit']);
$to = " Whoever <$email>";
$subject = 'Hello';
$message = "Hello, $firstname!";
if (mail($to, $subject, $message, $headers)){
$email = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I've also tried
$( document ).ready(function() {
$(".form_pro").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/interuni_process.php",
data: $(this).serialize(),
success: function(data) {
},
error: function() {
}
});
});
});
i think you have to change the logic flow to do so. try the following code which i have tested on my PC.
and sample code for "interuni_process.php" is
modify business logic as your per requirement
Firstly You remove action from HTML
<form>
Tagafter change add return false to your jquery function as per below