0
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 form’s original page, but for some reason the return is always displayed on the PHP page, I have tried to make several changes without success.
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;
});
O 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 tried to take the action out of the form, but it didn’t work. I also tried to put async in Jquery and it didn’t work, I’m really breaking my head.
About e.Prevent you had already tried using it. The error was even lower case. Amazing how we look at the N code sometimes and don’t find the error and sometimes need an outside help. Mt thanks, and also for the didactic form of response approach.
– lipitos
Nothing! Common mistake this, of those who get angry because everything seems right kk. Good projects!
– Victor Eyer