I decided to switch from a WordPress website to a self-made with HTML, CSS and JS, aiming to improve performance. So far, relying on tutorials, I've managed to deal with almost every issue, but I just can't get the contact form work the way it worked in WP. So far it redirects me to another page that shows the success message, which is just ugly.
Basically, I want the submit button to do 3 things: 1. Not to redirect me to another page. 2. Reset the form. 3. Display a success message.
Read many similar questions here, but as I am completely unfamiliar with AJAX, finally decided to post this question. Here's my code:
Index.html:
<div>
<form method="post" action="form.php" name="myForm">
<input name="name" placeholder="Nombre" required>
<input name="email" type="email" placeholder="Correo Electrónico" required>
<textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
<input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
</form>
</div>
and in form.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto@mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";
?>
Any help would be much appreciated.
Thanks.
Put an ID to your form
<form id='myForm'>
....
</form>
Use jQuery (For easy code)
....
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</body>
Use $.ajax
$('#myForm').submit(function(e) {
e.preventDefault(); // prevent from submitting form directly
$.ajax({
url: 'form.php',
method: 'post',
data: $("#myForm").serializeArray() // convert all form data to array (key:value)
})
.done(function(response){
alert(response); // show the response
$("#myForm").reset(); // reset the form
})
.fail(function(error){
alert(error); // show the error.
});
})