0

Attempting to send results from form by email.

I have a form that request user information like Name, email etc. I am able to retrieve this info using js. The problem I am encountering is when I pass the value to PHP using AJAX, no email is sent out. I checked and no errors are populating. I add code in the php to see what is not being pass and when I did, none of the values are being passed to the php file.

The following code is the form:

    <form name="sentMessage" id="contactForm">
              <div class="row">
                <div class="col-md-6">
                  <div class="form-group">
                    <input type="text" id="name" class="form-control" placeholder="Name" required="required">
                    <p class="help-block text-danger"></p>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group">
                    <input type="email" id="email" class="form-control" placeholder="Email" required="required">
                    <p class="help-block text-danger"></p>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <textarea id="message" class="form-control" rows="4" placeholder="Message" required="required"></textarea>
                <p class="help-block text-danger"></p>
              </div>
              <div id="success"></div>
              <button type="submit" class="btn btn-custom btn-lg">Send Message</button>
            </form>

and the following is the ajax call:

submitSuccess: function($form, event) {
   event.preventDefault(); // prevent default submit behaviour
   // get values from FORM
   var name = $("input#name").val();
   var email = $("input#email").val();
   var message = $("textarea#message").val();
   var firstName = name; // For Success/Failure Message
   // Check for white space in name for Success/Fail message
   if (firstName.indexOf(' ') >= 0) {
           firstName = name.split(' ').slice(0, -1).join(' ');
    }
    $.ajax({
        url: "./mail/contact_me.php",
        type: "POST",
       data: {
            name: name,
            email: email,
            message: message
        },
        cache: false,
        success: function() {
           // Success message
           $('#success').html("<div class='alert alert-success'>");
           $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
           .append("</button>");
          $('#success > .alert-success')
            .append("<strong>Your message has been sent. </strong>");
          $('#success > .alert-success')
              .append('</div>');

             //clear all fields
           $('#contactForm').trigger("reset");
         },
         error: function() {
          // Fail message
           $('#success').html("<div class='alert alert-danger'>");
           $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
             .append("</button>");
           $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
        $('#success > .alert-danger').append('</div>');
         //clear all fields
         $('#contactForm').trigger("reset");
      },
    })
 },

and here is the contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'rflores@RegalMed.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>

After the user submits the form, I should be able to receive in email with the users name, email and comments. Not sure if I am missing something. Am I passing the values incorrectly in the "data:{" part?

Any help would be appreciated.

ROB
  • 23
  • 7
  • are you targeting a correct path here - `url: "././mail/contact_me.php"` with `././`, `current dir/current dir` – jibsteroos Feb 11 '19 at 19:52
  • I didnt see that and I did removed the extra "./" However, it still shows the error that none of the values are being passed. I am seeing the following path on the console: http://portal/mysite/mail/contact_me.php – ROB Feb 11 '19 at 19:57
  • `contact_me.php` or `email.send.php`? – Louys Patrice Bessette Feb 11 '19 at 21:11
  • @LouysPatriceBessette contact_me.php. Where are you seeing email.send.php? – ROB Feb 11 '19 at 21:16
  • In the text above the PHP code. – Louys Patrice Bessette Feb 11 '19 at 21:20
  • @LouysPatriceBessette: Ahh okay. Sorry for the confusion. I have edited my question. – ROB Feb 11 '19 at 21:23
  • Try to replace `return false;` for `die();` and remove `return true;` for a start. Then look for `mail()` error management [here](https://stackoverflow.com/questions/3186725/how-can-i-get-the-error-message-for-the-mail-function) – Louys Patrice Bessette Feb 11 '19 at 21:28
  • 1
    @LouysPatriceBessette: The problem I am encountering that the mail does not fail. It sends a message saying that "Your Message has been Sent" – ROB Feb 11 '19 at 21:40
  • 1
    `Your message has been sent.` appears only because the Ajax request succeded. That does not mean the email is actually sent. So it's not an Ajax issue, but a PHP mail() issue. – Louys Patrice Bessette Feb 11 '19 at 21:42
  • @LouysPatriceBessette: You are right. I am confused still on why the values are not being passed correctly. It hits my error in the php file saying no arguments provided. – ROB Feb 11 '19 at 21:45

1 Answers1

0

That is not an Ajax issue, since you get the Your Message has been Sent. message, which is in the Ajax success callback.

So... You have to test your contact_me.php file and find what is going wrong.

Open that page directly from the address bar: http(s)://your-domain/mail/contact_me.php with this content:

<?php
// PHP error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check for empty fields ---- Comment that out temporarily...
/*
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['message'])     ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
     echo "No arguments Provided!";
}

// Post variables
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
*/

// Temporary for direct URL tests... Remove after!
$name = "John Doh";
$email_address = "jdoh@hotmail.com";
$message = "You fond John Doh!";

// Create the email and send the message
$to = 'rflores@RegalMed.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";

// Check if the mail function is enabled
if ( function_exists( 'mail' ) ){
  echo "mail() is available.";
}else{
  echo "mail() has been disabled";
  die();
}

// Try to sent the mail...
$mail_sent = mail($to,$email_subject,$email_body,$headers);

// Check if mail worked.
if(!mail_sent){
  echo "There was an error with the mail function<br>";
}else{
  echo "Mail() is working!";
}
?>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Wouldn't calling a non-existing function lead to a PHP error and therefore rendering echo "Probably because mail() has been disabled";unreachable? – Fitzi Feb 11 '19 at 22:43