I'm new to this and I do not know how to send form with php and ajax, in my statement in the else I used also default default so that it is not sent, like it is sent by ajax, but my question is, if I do prevent default, it is not going to be sent, then how do I do it? I want to get an alert with the errors inserted in the form and then an alert of the else, with my data and with a message to get in ph, the alert and everything works but I do not know how to make the form to be sent.
<?php
header('Access-Control-Allow-Origin: *');
$jsondata = array();
$jsondata['saludo'] = '¡Hola '. $_POST['campoNombre'] . '!';
$jsondata['telefono'] = 'Nos pondremos en contacto con ' . $_POST['campoEmail'] . ' lo antes posible';
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata);
exit();
if($_POST) {
$to_Email = "[email protected]"; // email de recepción
$subject = 'SOLICITUD DE CONTACTO'; // asunto
// saneado de seguridad
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
// composición de email
$headers = "MIME-Version: 1.0";
$headers .= "Content-type: text/html; charset=charset=UTF-8";
$headers .= 'From: SOLICITUD CONTACTO' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$body = "Se ha recibido una nueva solicitud de contacto:"."\r\n";
$body .= "Nombre: " . $user_Name ."\r\n";
$body .= "Correo: " . $user_Email ."\r\n";
$body .= "Mensaje: " . $user_Message ."\r\n";
// envío de email
$sentMail = @mail($to_Email, $subject, $body, $headers);
}
? >
$(document).ready(function(){
function validacionFormulario(){
$('form').on('submit', function(e){
let nombre = $('#campoNombre').val();
let email = $('#campoEmail').val();
let telefono = $('#campoTelefono').val();
let mensaje = $('#campoMensaje').val();
if (nombre.length <= 2) {
alertaError('El nombre es demasiado corto');
e.preventDefault();
}
else if (email.includes('@') == false || email.includes('.') == false || email.indexOf('@') < 1 || email.indexOf('.') < 3) {
alertaError('El email no es correcto');
e.preventDefault();
}
else if (telefono.length < 9) {
alertaError('El telefono debe tener al menos 9 numeros');
e.preventDefault();
}
else if (mensaje.length <= 10) {
alertaError('El mensaje es demasiado corto');
e.preventDefault();
}
else{
$.post({
url:'http://www.asociacionaepi.es/curso_web/francisco/practica1/contact.php',
data: $(this).serialize(),
success: function(datos) {
let texto = datos.saludo + ' ' + datos.telefono;
msg(texto, 2);
}
});
}
});
}
//ERROR MSG
function alertaError(texto){
$('#alerta p').text(texto);
$('#alerta').addClass('visible');
setTimeout(function(){
$('#alerta').removeClass('visible');
},3000);
}
// MSG
function msg(mensajes, tiempo) {
$('#alerta p').text(mensajes);
$('#alerta').addClass('visible');
setTimeout( function(){
$('#alerta').removeClass('visible');
},tiempo * 2000);
}
})
#alerta {
background: #8c8a8a;
border: 1px solid black;
border-radius: 2px;
position: fixed;
bottom: 100px;
-webkit-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;
-webkit-transform: translateX(-100%);
-ms-transform: translateX(-100%);
transform: translateX(-100%);
}
#alerta.visible {
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0);
}
#alerta p {
color: black;
line-height: 0;
margin: 3px;
font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>my page</title>
</head>
<body>
<form action="contact.php" method="post" id="formulario">
<div class="row">
<div class="col-sm-4">
<input id="campoNombre" name="campoNombre" type="text" placeholder="Nombre...">
</div>
<div class="col-sm-4">
<input id="campoEmail" name="campoEmail" type="text" placeholder="Email...">
</div>
<div class="col-sm-4">
<input id="campoTelefono" name="campoTelefono" type="text" placeholder="Telefono...">
</div>
<div class="col-xs-12">
<textarea id="campoMensaje" name="campoMensaje" type="text" placeholder="Mensaje..." rows="8" maxlength="999"></textarea>
</div>
<div class="col-xs-12">
<input type="submit" value="Enviar" class="boton">
</div>
</div>
</form>
</body>
</html>