1

I'm trying to submit a form which includes a select option. When the form is submitted through javascript it is validated and then posted into a php code to send an email. Everthing on the form works except for the select option value which is not being output in the email. Please find code below. The variable I'm interested in is $service. Currently the $service is output as blank in the email that I receive. Every other variable is working.

contact.php

<form name="sentMessage" id="contactForm" novalidate>
  <div class="control-group form-group">
    <div class="controls">
      <label>Full Name:</label>
      <input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
      <p class="help-block"></p>
    </div>
  </div>
  <div class="control-group form-group">
    <div class="controls">
      <label>Phone Number:</label>
      <input type="tel" class="form-control" id="phone" required data-validation-required-message="Please enter your phone number.">
    </div>
  </div>
  <div class="control-group form-group">
    <div class="controls">
      <label>Email Address:</label>
      <input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
    </div>
  </div>
  <div class="control-group form-group">
    <div class="controls">
      <label>Service Type:</label>
      <select name="service" id="service" class="form-control" required data-validation-required-message="Please select type.">
      <option value="service1">Service 1</option>
      <option value="service2">Service 2</option>
      <option value="service3">Service 3</option>
    </select>
    </div>
  </div>
  <div class="control-group form-group">
    <div class="controls">
      <label>Message:</label>
      <textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
    </div>
  </div>
  <div id="success"></div>
  <!-- For success/fail messages -->
  <button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>
</div>

contact_me.js

$(function() {

  $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    },
    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 phone = $("input#phone").val();
      var service = $("option#service").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(' ');
      }
      $this = $("#sendMessageButton");
      $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
      $.ajax({
        url: "./../mail/contact_me.php",
        type: "POST",
        data: {
          name: name,
          phone: phone,
          email: email,
          service: service,
          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>").text("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");
        },
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 1000);
        }
      });
    },
    filter: function() {
      return $(this).is(":visible");
    },
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});

contact_me.php

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

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$service = strip_tags(htmlspecialchars($_POST['service']));
$message = strip_tags(htmlspecialchars($_POST['message']));


// Create the email and send the message
$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - 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\nPhone: $phone\n\nService Type: $service\n\nMessage:\n$message";
$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

It is probably something obvious that I'm overlooking or I'm not on the right track at all. Thank you for your assistance.

Current output:

You have received a new message from your website contact form.

Here are the details:

Name: aksjdn

Email: [email protected]

Phone: laskjdfo23

Service Type:

Message:
askjfdnaskljdfn 21:57:45
3
  • I do have that already. As I stated, all the other variables do output properly except $service Commented Jun 29, 2020 at 11:56
  • 1
    Simply write $("#service").val() to get value of select in ajax . Commented Jun 29, 2020 at 12:07
  • Hi, I have tried this. $service is still blank. Commented Jun 29, 2020 at 22:42

2 Answers 2

2

I think your mistake is made by getting the value of the service. You are now doing:

var service = $("option#service").val();

But what you actually want to do is the following:

var service = $("select#service").val();
Sign up to request clarification or add additional context in comments.

2 Comments

I probably should have mentioned that I did try this before but still the $service variable is blank.
Ah okay. Try this: var service = $("select#service").children("option:selected").val();
0

I did a combo of the comment from Swati and Luke Hol to get the output.

var service = $("#service option:selected").val();

Thank you for your assistance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.