I have the following code with which I want to send an email (that works correctly) without having to refresh the page and also a div that I have with a display none change to flex. The two things separately work for me, the fault is to want to do everything together, that what happens is that the div is shown but the message is not sent. I hope your help, greetings!
<!--form without refreshing (ajax)-->
<script>
function chk(){
require_once('js/addcampos.php'); //aqui realizo el envio del mensaje
var dataModal = document.getElementById('modalSuccess');
$.ajax({
type:"post",
url:"<?php echo $_SERVER['PHP_SELF']; ?>",
cache:false,
success: function(){
$("#modalSuccess").css("display","flex");
$("form")[0].reset();
setTimeout("$('#modalSuccess').hide();", 3000);
}
});
return false;
}
</script>
<div id="formulario-email">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="email" placeholder="Introduce tu email" id="email"><br>
<input type="text" name="asunto" placeholder="Introduce el asunto del mensaje" id="asunto"><br>
<textarea name="mensaje" id="mensaje" placeholder="Introduce el cuerpo del mensaje" cols="30" rows="6"></textarea>
<input type="submit" onclick="return chk()" name="enviar" value="Enviar">
</form>
</div>
<div id="modalSuccess">
<span>Mensaje enviado correctamente</span>
</div>
</div>
</div>
<?php
if (isset($_POST['enviar'])) {
if (isset($_POST['asunto']) && isset($_POST['mensaje']) && isset($_POST['email'])) {
$email = $_POST['email'];
$mensaje = $_POST['mensaje'];
$asunto = $_POST['asunto'];
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html: charset=iso-8859-1\r\n";
$headers = "From:$email";
$bool = mail("[email protected]",$asunto,$mensaje,$headers);
if ($bool) {
header('Location: ' . $_SERVER['PHP_SELF']);
}
}else{
echo "Falta algo";
}
}
?>