douju7765 2015-09-21 11:25
浏览 28

使用Ajax上传PHP文件

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("","
"),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
";
    $email_content .= "Tel: $tel
";
    $email_content .= "Email: $email
";
    $email_content .= "Message: $message
";
    $email_content .= "Make/Brand: $make
";
    $email_content .= "Model: $model
";
    $email_content .= "Reference: $reference
";
    $email_content .= "Condition: $condition
";

    // 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.";
}

?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
    • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
    • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
    • ¥15 运动想象脑电信号数据集.vhdr
    • ¥15 三因素重复测量数据R语句编写,不存在交互作用
    • ¥15 微信会员卡等级和折扣规则
    • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
    • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
    • ¥15 gdf格式的脑电数据如何处理matlab
    • ¥20 重新写的代码替换了之后运行hbuliderx就这样了