Reputation: 1
I have a form, and when I submit it, it goes to another page.
To fix this, I left empty the action field in the html. But now, the php doesn't send the mail.
I want to stay on same page, send the mail and get a message confirmation.
I have not so much knowledge about this, and I can't fix it by myself.
Here is the code:
<form id="idForm"method="post" action="">
<div class="row 50%">
<div class="6u 12u$(mobile)"><input id="nome" required="required" type="text" class="text" name="name" placeholder="Nome" /></div>
<div class="6u$ 12u$(mobile)"><input id="email" required="required" type="email" class="text" name="email" placeholder="Correo electrónico" /></div>
<div class="12u$">
<textarea id="mensaxe" required="required" name="mensaxe" placeholder="Mensaxe"></textarea>
</div>
<div class="12u$">
<ul class="actions">
<li><input type="submit" value="Enviar mensaxe" />
<span id="message"></span>
</li>
</ul>
</div>
</div>
</form>
and here the php
<?php
if(isset($_POST['email'])) {
// Debes editar las próximas dos líneas de código de acuerdo con tus preferencias
$email_to = "[email protected]";
$email_subject = "Contacto desde el sitio web";
// Aquí se deberían validar los datos ingresados por el usuario
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['mensaxe'])) {
echo "<b>Ocurrió un error y el formulario no ha sido enviado. </b><br />";
echo "Por favor, vuelva atrás y verifique la información ingresada<br />";
die();
}
$email_message = "Detalles del formulario de contacto:\n\n";
$email_message .= "Nombre: " . $_POST['name'] . "\n";
$email_message .= "E-mail: " . $_POST['email'] . "\n";
$email_message .= "Comentarios: " . $_POST['mensaxe'] . "\n\n";
// Ahora se envía el e-mail usando la función mail() de PHP
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
}
?>
And the js
$("#idForm").submit(function() {
event.preventDefault();
var url = "../php/formulario.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
$("message").text("Success Message");
}
});
return false; // avoid to execute the actual submit of the form.
});
I appreciate any help!! Thanks.
Upvotes: 0
Views: 2281
Reputation: 436
in your js, you must change like this:
$("#idForm").submit(function(e) {
e.preventDefault();
for not send by post the form in the same page (action empty = same page )
And in your ajax, you have a mistake:
$("message").text("Success Message");
$("#message").text("Success Message"); //CORRECT with #
you can change function(data) for function(html) and make an alert(html) for see what the php page say .. ;)
Upvotes: 0
Reputation: 46
event is missing in the function parameter
$("#idForm").submit(function(event) {
Upvotes: 2