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.


<script type="text/javascript">
    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;
      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:

$to = "[email protected]";
$subject = "Email From User";

$message = "
<title>Email From User</title>
<p>This email contains User Requirement</p>

$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";

if ($ok) {
    echo "1";
    echo "0";



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

People are also looking for solutions to the problem: php - File upload using curl is not working


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.