I am passing form data via Ajax, and would like the return to be displayed on my html page on <div id=resposta></div>
, on the original page of the form, however for some reason the return is always displayed on the PHP page, I have already tried to do several unsuccessful changes.
The html form:
<form id="contactForm" method="post" action="php/form-process.php">
<input type="text" class="form-control" id="name" name="name" placeholder="Preencha seu nome" required data-error="Preencha o Nome">
<input type="text" id="email" class="form-control" name="email" placeholder="Preencha seu e-mail" required data-error="Preencha o E-mail">
<input type="text" id="phone" class="form-control" name="phone" placeholder="Preencha um telefone para contato" required data-error="Preencha um telefone para Contato">
Tipo de Conta:
<label><input type="radio" name="account" id="pessoal">Pessoal</label>
<label><input type="radio" name="account" id="profissional">Profissional</label>
<textarea class="form-control" id="message" name="message" placeholder="Sua Mensagem" rows="8" data-error="Escreva sua Mensagem" required></textarea>
<button class="btn btn-common" id="submit" type="submit">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div id="resp"></div>
The Jquery Code:
$('#contactform').submit(function(e) {
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
var phone = $('input[name="phone"]').val();
var account = $('input[name="account"]').val();
var message = $('textarea[name="message"]').val();
$.ajax({
url: 'php/form-process.php', // caminho para o script que vai processar os dados
async: false,
type: 'POST',
data: {
name: name,
email: email,
phone: phone,
account: account,
message: message
},
dataType: 'html',
success: function(response) {
$('#resp').html(response);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});
The PhP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$account = $_POST['account'];
$message = $_POST['message'];
$response = "";
$response .= "<div class=\"success\" id=\"resp\">";
$response .= " <a href=\"#\" class=\"close\" aria-label=\"close\">×</a>";
$response .= "<strong> Enviado com sucesso! </strong>";
$response .= "</div>";
echo($response);
?>
I've tried to take action from the form, but it did not work. I tried also to put the async in Jquery and it did not work, I'm really breaking the head.