phpjqueryajaxjquery-3

jQuery 3 + Ajax + PHP send mail form not sending mail


I've been trying to re-write a jQuery + PHP send mail form but despite trying 3 methods it's still throwing a 500 Internal Server Error. I'm rewriting because I'm migrating the site to jQuery 3 and working on improving performance and standards compliance with a codebase I've inherited.

I know 500 is a server error and the site is hosted on MS IIS, but the legacy code is working on the same server, so there must be something specific to my implementation.

Maybe you can see something I've missed?

The below code mostly follows this example on Stack Overflow but I've also tried following this youtube and this tutorial without success.

Hoping for an answer here after exhausting my other options. Thanks in advance!

HTML (simplified)

<form action="send_mail_facility2.php" id="facility-contact-form" method="post" autocomplete="on">
  <!-- MAIN FIELDS -->
  <input id="sendTo" name="sendTo" type="text" value="Facility One" style="display: none;">
  <input id="name" name="name" type="text" placeholder="Name" required>
  <input id="email" name="email" type="email" placeholder="Email" required>
  <input id="phone" name="phone" type="text" placeholder="Phone number">
  <textarea id="message" name="message" type="text" placeholder="Message"></textarea>

  <!-- ADDITIONAL FIELDS - separate js shows section when checkbox selected -->
  <input id="infopack-checkbox" type="checkbox" name="checkbox" value="checkbox"><span class="information-pack">&nbsp;I would like to receive an information pack.</span>
  <div id="address-details">
    <input id="address" name="address" type="text" placeholder="Address">
    <input id="city" name="city" type="text" placeholder="City">
    <input id="postcode" name="postcode" type="text" placeholder="Postcode">
  </div>

  <!-- reCAPTCHA html & js -->

  <input id="facility-submit" name="submit" type="submit" value="Send request" disabled style="opacity: 0.3;"> <!-- disabled & inline style for captcha -->
  <p class="status" style="display: none" role="alert">Thanks, someone will be in contact with you regarding your enquiry soon.</p>
</form>

JS

$(function(){
  var request;
  $("#facility-contact-form").on("submit", function(event){
    event.preventDefault();
    if (request) {
      request.abort();
    }
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializeData = $form.serialize();
    $inputs.prop("disabled", true);
    request = $.ajax({
      url: "send_mail_facility2.php",
      type: "post",
      data: serializeData
    });
    request.done(function (response, textStatus, jqXHR){
      console.log("Hooray, it worked!");
    });
    request.fail(function (jqXHR, textStatus, errorThrown){
      console.error("The following error occurred: "+
                   textStatus, errorThrown);
    });
    request.always(function () {
      $inputs.prop("disabled", false);
    });
  });
});

PHP

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // email headers
  $to       = $_POST["sendTo"];
  $subject  = "Custom subject line";
  $headers  = "From: NoReply &lt;noreply@noreply.com&gt;";

  // sender data
  $name     = $_POST["name"];
  $email    = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
  $phone    = trim($_POST["phone"]);
  $message  = trim($_POST["message"]);
  $address  = isset($_POST["address"]) ? trim($_POST["address"]) : null;
  $city     = isset($_POST["city"]) ? trim($_POST["city"]) : null;
  $postcode = isset($_POST["postcode"]) ? trim($_POST["postcode"]) : null;

  //define recipients
  $sendTo = $_POST["sendTo"];

  if($sendTo == 'Facility One') {
    $to = 'mytestemail@example.com';
  } elseif($sendTo == 'Facility Two') {
    $to = 'two@clientemail.com';
  } elseif($sendTo == 'Facility Three') {
    $to = 'three@clientemail.com';
  }

  if (isset($_POST['checkbox'])) {
    $infoPack = "Yes";
  } else {
    $infoPack = "No";
  }
  if (empty($_POST["address"])) {
    $address = "N/A";
  } else {
  }
  if (empty($_POST["city"])) {
    $city = "N/A";
  } else {
  }
  if (empty($_POST["postcode"])) {
    $postcode = "N/A";
  } else {
  }

  // email content
  $content = "Enquiry for facility: $sendTo\n\n";
  $content .= "Name: $name\n\n";
  $content .= "Email: $email\n\n";
  $content .= "Phone: $phone\n\n";
  $content .= "Message:\n$message\n\n";
  $content .= "Would user like to receive an information pack?: $infoPack\n\n";
  $content .= "Address: $address\n\n";
  $content .= "City: $city\n\n";
  $content .= "Postcode: $postcode\n\n\n";
  $content .= "Static footer message here\n\n";

  // Send the email
  $success = mail($to, $subject, $content, $headers);
  if ($success) {
    http_response_code(200);
    echo "Thanks, someone will be in contact with you regarding your enquiry soon.";
  } else {
    http_response_code(500);
    echo "Oops, something went wrong - we couldn't send your message.";
  }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "Oops, something went wrong - we couldn't send your message.";
}

Any ideas?


Solution

  • Thanks to @Darren who pointed me to the error response.

    The problem appears to have just been the from header syntax which I copied from step 3 of this tutorial.

    I changed:

    $headers  = "From: NoReply &lt;noreply@noreply.com&gt;";
    

    to:

    $headers = "FROM: NoReply <noreply@noreply.com>";
    

    I didn't get this from the question/answer that was listed as a duplicate, as useful as that answer is.

    For other PHP newbies, use Firefox/Chrome developer tools Network tab, run through submitting your form, filter for your php file and then look at the Response tab to see the full response with any errors.