I am trying to submit a form with PHPMailer by making an AJAX request to display a success window when completing the request.
My question is that I have another form (form-4) that does the whole process for me perfectly and I don't understand this error with my second form (form-1) that is on the same page, both differentiated by ID.
What I have tried :
*Try' submitting the form without the AJAX request and it submits perfectly (in the form action), but I get an HTTP500 even though I tell it to show me an Alert(); this is why I decided to make the AJAX request.
*I am showing in the console the validation processes of my form (Error and success), when there is an error in the form it shows me the error message, but the success message does not show it to me and I do not receive the message either; so I think the whole problem is in this request.
$.validate({
modules : 'security',
onError : function($form1) {
console.log('validation error');
$('html, body').animate({
scrollTop: $('.form-error').offset().top
}, 500);
},
onSuccess : function($form1) {
if(($form1).attr('id') === 'form-1'){
console.log('validation success');
$.ajax({
type: "POST",
url: "php/websiteEmail.php",
data: $form1.serialize(),
success: function(){
$('.js-form-1-response').addClass('sent');
$('.js-form-1-response').html('<h2>Excelente!</h2> <p>¡Es un placer conocerte! Danos un par de horas y programaremos nuestra primera cita.</p><a class="bs-button btn-small" data-linkName="Ir al inicio" href="/"><span data-hover="Ir al inicio">Ir al inicio</span></a><h6>Revisa nuestros canales creativos</h6><ul class="social"><li class="dribbble"><a href="" target="_blank"><span>Dribbble</span><img src="img/social/social-dribbble-loop.gif" alt="Dribbble"></a><li><li class="behance"><a href="" target="_blank"><span>Behance</span><img src="img/social/social-behance-loop.gif" alt="Behance"></a><li><li class="instagram"><a href="" target="_blank"><span>instagram</span><img src="img/social/social-instagram-loop.gif" alt="Instagram"></a><li></ul>');
}
});
}else{
$.ajax({
type: "POST",
url: "php/websiteEmail.php",
data: $form1.serialize(),
success: function(){
$('.js-form-1-response').addClass('sent');
$('.js-form-1-response').html('<h2>Excelente!</h2> <p>¡Es un placer conocerte! Danos un par de horas y programaremos nuestra primera cita.</p><a class="bs-button btn-small" data-linkName="Ir al inicio" href="/"><span data-hover="Ir al inicio">Ir al inicio</span></a><h6>Revisa nuestros canales creativos</h6><ul class="social"><li class="dribbble"><a href="" target="_blank"><span>Dribbble</span><img src="img/social/social-dribbble-loop.gif" alt="Dribbble"></a><li><li class="behance"><a href="" target="_blank"><span>Behance</span><img src="img/social/social-behance-loop.gif" alt="Behance"></a><li><li class="instagram"><a href="" target="_blank"><span>instagram</span><img src="img/social/social-instagram-loop.gif" alt="Instagram"></a><li></ul>');
}
});
}
},
});
$('body').on('click', '.js-remove-msg', function(){
$('.js-form-1-response').text('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<form action="" method="post" id="form-1">
<div id="web-step-3" class="step step-3">
<div class="offset-top-sm">
<div class="row center-xs">
<div class="col-xs-12 col-sm-9 col-md-7">
<div class="step-number"><strong>03</strong> - 04</div>
<h2>Detalles del <br />proyecto</h2>
</div>
</div>
<div class="form-wrap">
<div class="row center-xs">
<div class="col-xs-12 col-sm-10 col-md-8">
<div class="row">
<div class="col-xs-12 col-lg-6">
<p>
<input class="text-input" name="your-name" type="text"
placeholder="Nombre *" data-validation="length"
data-validation-length="min2"
data-validation-error-msg="Introduzca su nombre">
</p>
</div>
<div class="col-xs-12 col-lg-6">
<p>
<input class="text-input" name="your-email" type="email"
placeholder="Correo *" data-validation="email required"
data-validation-error-msg="Introduzca un correo">
</p>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-lg-6">
<input class="text-input" name="your-phone" type="text"
placeholder="Celular">
</div>
<div class="col-xs-12 col-lg-6">
<input class="text-input" name="your-company-name" type="text"
placeholder="Nombre Empresa">
</div>
</div>
<div class="row">
<div class="col-xs-12">
<input class="text-input" name="your-company-url" type="text"
placeholder="Url del sitio">
</div>
<p>
<input type="checkbox" name="contact_me_by_fax_only" value="1"
style="display:none !important" tabindex="-1"
autocomplete="false">
</p>
</div>
</div>
</div>
</div>
</div>
<div style="text-align:center">
<a class="bs-button btn-small" href="#web-step-4" data-anchor="web-step-4" data-linkName="Siguiente">
<span data-hover="Siguiente">Siguiente</span></a>
</div>
</div>
<!-- End of step 4 -->
<div id="web-step-4" class="step step-4">
<div class="offset-top-sm">
<div class="row center-xs">
<div class="col-xs-12 col-sm-9 col-md-7">
<div class="step-number"><strong>04</strong> - 04</div>
<h2>Algo más?</h2>
<div class="row center-xs">
<div class="col-xs-12 col-md-10">
<p class="small">Si hay algún detalle pertinente que le gustaría
compartir, deje un mensaje en el cuadro a continuación.</p>
</div>
</div>
</div>
</div>
<div class="form-wrap">
<div class="row center-xs">
<div class="col-xs-12 col-md-6">
<textarea rows="4" cols="50" placeholder="Esperamos su comentario..."
name="additional-info"></textarea>
</div>
</div>
<div class="row center-xs">
<div class="col-xs-8 col-sm-4 col-lg-3">
<div class="submit-button-wrap">
<input name="submit-website" class="submit-button" type="submit"
value="ENVIAR INFO">
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End of step 4 -->
</form>
As Extra information, when pressing Send Info, it shows me an Error: POST in ..php/email.php I understand perfectly that this is my file to send the mail but from my other form ID: form-4 , the current one is .. .php/websiteEmail.php of my form ID: form-1 .
To validate my form ID: form-4 I use this request:
//Form-4
$.validate({
modules : 'security',
onError : function($form) {
console.log('validation error');
$('html, body').animate({
scrollTop: $('.form-error').offset().top
}, 500);
},
onSuccess : function($form) {
if(($form).attr('id') === 'form-4'){
console.log('validation success');
$.ajax({
type: "POST",
url: "php/email.php",
data: $form.serialize(),
success: function(){
$('.js-form-response').addClass('sent');
$('.js-form-response').html('<h2>Excelente!</h2> <p>¡Es un placer conocerte! Danos un par de horas y programaremos nuestra primera cita.</p><a class="bs-button btn-small" data-linkName="Ir al inicio" href="/"><span data-hover="Ir al inicio">Ir al inicio</span></a><h6>Revisa nuestros canales creativos</h6><ul class="social"><li class="dribbble"><a href="https://dribbble.com/Buzzworthy" target="_blank"><span>Dribbble</span><img src="img/social/social-dribbble-loop.gif" alt="Dribbble"></a><li><li class="behance"><a href="https://www.behance.net/BuzzworthyStudio" target="_blank"><span>Behance</span><img src="img/social/social-behance-loop.gif" alt="Behance"></a><li><li class="instagram"><a href="https://www.instagram.com/buzzworthy.studio/" target="_blank"><span>instagram</span><img src="img/social/social-instagram-loop.gif" alt="Instagram"></a><li></ul>');
}
});
}else{
$.ajax({
type: "POST",
url: "php/email.php",
data: $form.serialize(),
success: function(){
$('.js-form-response').addClass('sent');
$('.js-form-response').html('<h2>Excelente!</h2> <p>¡Es un placer conocerte! Danos un par de horas y programaremos nuestra primera cita.</p><a class="bs-button btn-small" data-linkName="Ir al inicio" href="/"><span data-hover="Ir al inicio">Ir al inicio</span></a><h6>Revisa nuestros canales creativos</h6><ul class="social"><li class="dribbble"><a href="" target="_blank"><span>Dribbble</span><img src="img/social/social-dribbble-loop.gif" alt="Dribbble"></a><li><li class="behance"><a href="" target="_blank"><span>Behance</span><img src="img/social/social-behance-loop.gif" alt="Behance"></a><li><li class="instagram"><a href="" target="_blank"><span>instagram</span><img src="img/social/social-instagram-loop.gif" alt="Instagram"></a><li></ul>');
}
});
}
},
});
* Edit:
<?php
require ('class.phpmailer.php');
require('PHPMailerAutoload.php');
$correo=trim($_POST['email']);
$nombre= trim($_POST['name']);
$mensaje = trim($_POST['message']);
// $apellido=trim($_POST['lastname']);
// $celular = trim($_POST['phone']);
$mail = new PHPMailer(true); // Enable verbose debug output
$mail->CharSet = "utf-8";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxx.com'; // SMTP username
$mail->Password = 'xxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to // TCP port to connect to
$mail->setFrom($correo, $nombre);
$mail->addAddress('[email protected]', 'Test');
$mail->addReplyTo($correo, 'Gracias por contactarnos');
$mail->isHTML(true);
$mail->Subject = 'Chat';
$mail->Body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="initial-scale=1.0" />
<meta name="format-detection" content="telephone=no" />
<title>'.$nombre.'</title>
</head>
<body id="body-layout" style="background: #406c8d;">
mensaje
</body>
</html>';
if(!$mail -> send()) {
$signal = 'bad';
$msg = 'Mailer Error: ' . $mail -> ErrorInfo;
} else {
echo'<script type="text/javascript">
alert("Mensaje enviado! en breve nos comunicaremos con usted.");
window.location.href="../index.php";
</script>';
$signal = 'ok';
$msg = '¡Tu Solicitud ha sido enviada! Pronto nos estaremos poniendo en contacto contigo.';
}
$data = array(
'signal' => $signal,
'msg' => $msg
);
echo json_encode($data);
Hello thanks to the comments I received I managed to find how to solve it.
My $.validate event that comes from a Validate.js library, at the time of integration I had not read its documentation very well.
By calling onError and onSuccess I can set the number of actions I want my/my forms to perform once the submit button is pressed.
So onSuccess I can add as many conditions as necessary, in the elseif/else I add all the forms that I want to validate based on their ID.
Now both forms send perfectly and I'll be adding my other forms right there.
Thanks for your comments.