php - Javascript Ajax - Contact form does not display prompts and send button doesn't work
I was looking on different examples for contact form sent using Javascript / AJAX. but the solutions don't seems to work. I'm trying to rewrite an existing chunk of code. Here is what I was left with (with a few of my own modifications).
I don't quite understand that where the functionality was going wrong. The send button does nothing, does not send to email and just goes to the top of the page.
Javascript:
<script type="text/javascript">
$('#submit').click(function(){
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var message = $("#message").val();
if (name == "") {
$('.errormess').html('<div ><strong>Please Insert Your name</strong></div>');
return false;
}
if (email == "") {
$('.errormess').html('<div ><strong>Please Insert Your Email</strong></div>');
return false;
}
if (phone == "") {
$('.errormess').html('<div ><strong>Please Insert Your Phone Number</strong></div>');
return false;
}
if (message == "") {
$('.errormess').html('<div ><strong>Please Insert Some Text</strong></div>');
return false;
}
$.ajax({
type: "POST",
url: 'contact-us.php',
data: 'name='+$("#name").val() +
'email='+$("#email").val() +
'phone=' + $("#phone").val()
+ 'message=' + $("#message").val(),
dataType: "html",
success: function(data) {
if (data == 0) {
$('.errormess').html('<div ><strong>Your Query Submited Successfully</strong></div>');
} else {
$('.errormess').html('<div ><strong>Failed To Send the Email</strong></div>');
}
}
});
return true;
});
This is the contact-us.php:
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$to = "[email protected]";
$subject = "Email From User";
$message = "
<html>
<head>
<title>Email From User</title>
</head>
<body>
<p>This email contains User Requirement</p>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Message</th>
</tr>
<tr>
<td>".$name."</td>
<td>".$email."</td>
<td>".$phone."</td>
<td>".$message."</td>
</tr>
</table>
</body>
</html>
";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$ok=mail($to,$subject,$message,$headers);
if ($ok) {
echo "1";
}
else{
echo "0";
}
?>
Answer
Solution:
I think the the problem is with your data in ajax. Either send it in object from like {name:$("#name").val(),email:$("#name").val(),...} or add "&" in-front of each key like ( '&name='+$("#name").val() + '&email='+$("#email").val() ). Hope this helps