0

I am working on a form where we need to upload the file. The form is processing with Ajax and the data is being posted on the email with no problem except file upload.

Now we want to allow user to upload multiple image files that will be stored on our server and we will get the link to the images in the email.

Please have a look at the codes below:

Form HTML code:

    <div class="col-sm-12">
      <div class="well">
        <form id="ajax-contact" action="http://websitename.com/mailer.php" method="post" enctype="multipart/form-data">

        <h2>Personal Details</h2>


        <div class="login-wrap">

          <div class="form-group">
            <label class="control-label" for="name">Name</label>
            <input name="name" placeholder="enter your name" id="name" class="form-control" type="text">
          </div>




          <div class="form-group">
            <label class="control-label" for="tel">Telephone</label>
            <input name="tel" placeholder="enter your telephone" id="tel" class="form-control" type="text">
          </div>




          <div class="form-group">
            <label class="control-label" for="email">Email</label>
            <input name="email" placeholder="enter your email" id="input-email" class="form-control" type="text">
          </div>




          <div class="form-group">
            <label class="control-label" for="comments">Comments</label>
            <textarea name="comments" placeholder="your comments" id="comments" class="form-control" type="text"></textarea>
          </div>


       </div>



        <h2 style="margin-top:20px;">Product Details</h2>


        <div class="login-wrap">

          <div class="form-group">
            <label class="control-label" for="make">Make/Brand</label>
            <input name="make" placeholder="enter your make" id="make" class="form-control" required="" type="text">
          </div>




          <div class="form-group">
            <label class="control-label" for="model">Model</label>
            <input name="model" placeholder="enter your model" id="model" class="form-control" required="" type="text">
          </div>




          <div class="form-group">
            <label class="control-label" for="reference">Reference Number</label>
            <input name="reference" placeholder="enter your reference" id="reference" class="form-control" type="text">
          </div>



          <div class="form-group">
            <label class="control-label" for="condition">Condition</label>
              <select id="condition" name="condition" required="">
                <option>Mint</option>
                <option>Used</option>
              </select>
          </div>



          <div class="form-group">
            <label for="images">Upload Images</label>
            <input id="images" name="images" multiple="" required="" type="file">
            <p class="help-block">upload maximum 4 images</p>


          </div>



          <div class="form-group">
            <label class="control-label" for="price">Expected Price</label>
            <input name="price" placeholder="enter your price" id="price" class="form-control" required="" type="text">
          </div>



          <div class="checkbox">
            <label>
              <input value="" type="checkbox">
              With Box
            </label>
          </div>


          <div class="checkbox disabled">
            <label>
              <input value="" type="checkbox">
              With Papers
            </label>
          </div>



       </div>



        <input value="Submit" class="btn btn-primary button" type="submit">

        </form>
      </div>
    </div>
  </div>

AJAX:

$(function() {
// Get the form.
var form = $('#ajax-contact');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        $('#message').val('');
        $('#tel').val('');
        $('#make').val('');
        $('#model').val('');
        $('#reference').val('');
        $('#condition').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
        }
    });

});

});

PHP Form Processor:

<?php

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $tel = filter_var(trim($_POST["tel"]));
    $message = trim($_POST["message"]);
    $make = trim($_POST["make"]);
    $model = trim($_POST["model"]);
    $reference = trim($_POST["reference"]);
    $condition = trim($_POST["condition"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "myemail@mycompany.com";

    // Set the email subject.
    $subject = "New Contact form Submitted";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Tel: $tel\n";
    $email_content .= "Email: $email\n";
    $email_content .= "Message: $message\n";
    $email_content .= "Make/Brand: $make\n";
    $email_content .= "Model: $model\n";
    $email_content .= "Reference: $reference\n";
    $email_content .= "Condition: $condition\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>
Alrick
  • 91
  • 2
  • 10

0 Answers0