javascript - PHP、jQuery、Ajax、发送带有附件字段代码的 HTML 输入字段不起作用

标签 javascript php jquery html ajax

我尝试在单击按钮时发送带有可选附件的电子邮件,并在表单字段上方显示结果。我已经编写了以下代码,但它不起作用(当我单击提交按钮时没有任何反应;想创建一个 fiddle ,但 JSFiddle 不接受 PHP 代码):

这是 HTML:

  <div id="contactSubmitResult"></div>
      <div id="contactSubmitResult"></div>
      <div id="contactForm">
        <div class="col1">
          <label for="form_firstname">Firstname <span class="required">*</span></label>
          <input type="text" id="form_firstname" name="form_firstname" value="" required />
        </div>
        <div class="col2">
          <label for="form_lastname">Lastname <span class="required">*</span></label>
          <input type="text" id="form_lastname" name="form_lastname" value="" required />
        </div>
        <div class="col1">
          <label for="form_address">Address</label>
          <input type="text" id="form_address" name="form_address" value="" />
        </div>
        <div class="col2">
          <label for="form_city">City</label>
          <input type="text" id="form_city" name="form_city" value="" />
        </div>
        <div class="col1">
          <label for="form_email">Email <span class="required">*</span></label>
          <input type="email" id="form_email" name="form_email" value="" required />
        </div>
        <div class="col2">
          <label for="form_phone">Phone <span class="required">*</span></label>
          <input type="tel" id="form_phone" name="form_phone" value="" required />
        </div>
        <div class="col12">
          <label for="form_attachment">Add Attachment</label>
          <input type="file" id="form_attachment" name="form_attachment" />
        </div>
        <div class="col12">
          <label for="form_message">Message <span class="required">*</span></label>
          <textarea id="form_message" name="form_message" required></textarea>
        </div>
        <div class="col12">
          <input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
        </div>
      </div>

这是 JavaScript:

    <script type="text/javascript" src="http://jdoe.com/js/jquery-1.11.1.min.js"></script>

    <!-- validate and submit form input -->
    <script type="text/javascript">

  $(document).ready(function() {

    matchFormFields = "#contactForm input[required], #contactForm textarea[required]";

    matchContactSubmitResult = "#contactSubmitResult";

    errorColor = 'red';

    $("#form_send").click(function() { 

      var formIsValid = true;

      // loop through each field and change border color to red for invalid fields       

      $(matchFormFields).each(function() {

        $(this).css('border-color', '');

        // check whether field is empty

        if(!$.trim($(this).val())) {

          $(this).css('border-color', errorColor);

          formIsValid = false;

        }

        // check whether email is valid

        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 

        if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {

          $(this).css('border-color', errorColor);

          formIsValid = false;

        }   

      });

      // submit data to server if form field contents are valid

      if (formIsValid) {

        // retrieve input field values to be sent to server

        var post_data = new FormData();
        post_data.append('form_firstname',  $('input[name=form_firstname]').val());
        post_data.append('form_lastname',   $('input[name=form_lastname]').val());
        post_data.append('form_address',    $('input[name=form_address]').val());
        post_data.append('form_city',       $('input[name=form_city]').val());
        post_data.append('form_email',      $('input[name=form_email]').val());
        post_data.append('form_phone',      $('input[name=form_phone]').val());
        post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
        post_data.append('form_message',    $('textarea[name=form_message]').val());

        // Ajax post data to server

        $.ajax({
          url: 'http://jdoe.com/sendContactFormEmail.php',
          data: post_data,
          contentType: false,
          processData: false,
          type: 'POST',
          dataType: 'json',
          success: function(response) {  

            if (response.type == 'error') { // load json data from server and output message

              output = '<div class="error">' + response.text + '</div>';

            } else {

              output = '<div class="success">' + response.text + '</div>';

              // reset values in all form fields

              $(matchFormFields).val('');

            }

            // display an animation with the form submission results

            $(matchContactSubmitResult).hide().html(output).slideDown();

          }

        });

      }

    });

    // reset border on entering characters in form fields

    $(matchFormFields).keyup(function() {

      $(this).css('border-color', '');

      $(matchContactSubmitResult).slideUp();

    });

  });

    </script>

以下是接收 jQuery AJAX POST 请求的 PHP 代码:

<?php

      //$output = json_encode(array('type'=>'error', 'text' => 'Yes'));

      //die($output);

  include("settings.php");

  $boundaryString = "generateboundaryfromthis";

  $to_email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4228262d2702252f232b2e6c212d2f" rel="noreferrer noopener nofollow">[email protected]</a>";

  $from_email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e70716c7b6e72675e747a717b307d7173" rel="noreferrer noopener nofollow">[email protected]</a>";

  $replyTo_email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84eaebf6e1f4e8fdc4eee0ebe1aae7ebe9" rel="noreferrer noopener nofollow">[email protected]</a>";

  if (isset($_POST)) {

    // check whether this is an ajax request, exit if not

    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

      $output = json_encode(array(
        'type' =>' error', 
        'text' => 'Ajax POST request expected.'
      ));

      die($output); //exit script outputting json data

    } 

    // retrieve sanitized input data

    $form_firstname  = filter_var($_POST["form_firstname"], FILTER_SANITIZE_STRING);
    $form_lastname   = filter_var($_POST["form_lastname"], FILTER_SANITIZE_STRING);
    $form_address    = filter_var($_POST["form_address"], FILTER_SANITIZE_STRING);
    $form_city       = filter_var($_POST["form_city"], FILTER_SANITIZE_STRING);
    $form_email      = filter_var($_POST["form_email"], FILTER_SANITIZE_EMAIL);
    $form_phone      = filter_var($_POST["form_phone"], FILTER_SANITIZE_NUMBER_INT);
    $form_message    = filter_var($_POST["form_message"], FILTER_SANITIZE_STRING);

    $email_body = <<<EOT
Firstname: $form_firstname
Lastname: $form_lastname
Address: $form_address
City: $form_city
E-mail: $form_email
Phone: $form_phone
Message:
$form_message
EOT;

    // retrieve attached file

    $hasAttachment = false;

    if (isset($_FILES["form_attachment"])) {

      $hasAttachment = true;

      $fileTmpName = $_FILES["form_attachment"]['tmp_name'];
      $fileName    = $_FILES["form_attachment"]['name'];
      $fileSize    = $_FILES["form_attachment"]['size'];
      $fileType    = $_FILES["form_attachment"]['type'];
      $fileError   = $_FILES["form_attachment"]['error'];

      $handle = fopen($fileTmpName);

      $content = fread($handle, $fileSize);

      fclose($handle);

      $encodedContent = chunk_split(base64_encode($content));

    }

    if ($hasAttachment) {

      // user submitted an attachment

      $boundary = md5($boundaryString);

      // header

      $headers = "MIME-Version: 1.0\r\n"; 
      $headers .= "From:" . $from_email . "\r\n"; 
      $headers .= "Reply-To: " . $replyTo_email . "\r\n";
      $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

      // plain text 

      $body = "--$boundary\r\n";
      $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
      $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
      $body .= chunk_split(base64_encode($email_body)); 

      // attachment

      $body .= "--$boundary\r\n";
      $body .="Content-Type: $fileType; name=\"$fileName\"\r\n";
      $body .="Content-Disposition: attachment; filename=\"$fileName\"\r\n";
      $body .="Content-Transfer-Encoding: base64\r\n";
      $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
      $body .= $encodedContent; 

    } else {

      // user did not submit an attachment

      $headers = "From:" . $from_email . "\r\n" .
                 "Reply-To: " . $replyTo_email . "\n" .
                 "X-Mailer: PHP/" . phpversion();

      $body = $email_body;

    }

    $mailSentSuccessfully = mail($to_email, $subject, $body, $headers);

    if ($mailSentSuccessfully) {

      //$output = json_encode(array('type'=>'message', 'text' => $pageSettings->getContents("mailSentSuccess")));
      $output = json_encode(array('type'=>'message', 'text' => 'Message sent.'));

      die($output);

    } else {

      //$output = json_encode(array('type'=>'error', 'text' => $pageSettings->getContents("mailSentFailure")));
      $output = json_encode(array('type'=>'error', 'text' => 'Error encountered. Message not sent.'));

      die($output);

    }

  }

最佳答案

一个问题:你忘记在

中添加 html 标签
matchContactSubmitResult = "#contactSubmitResult";

添加

<div id="contactSubmitResult"></div>

这是片段。我冒昧地提供了 success: function(){} 的替代方案,而是使用 .done().fail()提供网络或其他问题。参见这里:jQuery.ajax() (我无法测试你的php代码,但你的jquery代码可以工作)

$(document).ready(function() {

    matchFormFields = "#contactForm input[required], #contactForm textarea[required]";

    matchContactSubmitResult = "#contactSubmitResult";

    errorColor = 'red';

    $("#form_send").click(function() { 

      var formIsValid = true;

      // loop through each field and change border color to red for invalid fields       

      $(matchFormFields).each(function() {

        $(this).css('border-color', '');

        // check whether field is empty

        if(!$.trim($(this).val())) {

          $(this).css('border-color', errorColor);

          formIsValid = false;

        }

        // check whether email is valid

        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 

        if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {

          $(this).css('border-color', errorColor);

          formIsValid = false;

        }   

      });

      // submit data to server if form field contents are valid

      if (formIsValid) {

        // retrieve input field values to be sent to server

        var post_data = new FormData();
        post_data.append('form_firstname',  $('input[name=form_firstname]').val());
        post_data.append('form_lastname',   $('input[name=form_lastname]').val());
        post_data.append('form_address',    $('input[name=form_address]').val());
        post_data.append('form_city',       $('input[name=form_city]').val());
        post_data.append('form_email',      $('input[name=form_email]').val());
        post_data.append('form_phone',      $('input[name=form_phone]').val());
        post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
        post_data.append('form_message',    $('textarea[name=form_message]').val());

        // Ajax post data to server

        $.ajax({
          url: 'http://jdoe.com/sendContactFormEmail.php',
          data: post_data,
          contentType: false,
          processData: false,
          type: 'POST',
          dataType: 'json'

        }) .done(function(response) {  

            if (response.type == 'error') { // load json data from server and output message

            output = '<div class="error">' + response.text + '</div>';

            } else {

              output = '<div class="success">' + response.text + '</div>';

              // reset values in all form fields

              $(matchFormFields).val('');

            }
$(matchContactSubmitResult).hide().html(output).slideDown();


          }).
          fail( function(response){
              output = '<div class="error"> NetWork Problems</div>';
          $(matchContactSubmitResult).hide().html(output).slideDown();

            });
        
      }

    });

    // reset border on entering characters in form fields

    $(matchFormFields).keyup(function() {

      $(this).css('border-color', '');

      $(matchContactSubmitResult).slideUp();

    });

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contactForm">
        <div class="col1">
          <label for="form_firstname">Firstname <span class="required">*</span></label>
          <input type="text" id="form_firstname" name="form_firstname" value="" required />
        </div>
        <div class="col2">
          <label for="form_lastname">Lastname <span class="required">*</span></label>
          <input type="text" id="form_lastname" name="form_lastname" value="" required />
        </div>
        <div class="col1">
          <label for="form_address">Address</label>
          <input type="text" id="form_address" name="form_address" value="" />
        </div>
        <div class="col2">
          <label for="form_city">City</label>
          <input type="text" id="form_city" name="form_city" value="" />
        </div>
        <div class="col1">
          <label for="form_email">Email <span class="required">*</span></label>
          <input type="email" id="form_email" name="form_email" value="" required />
        </div>
        <div class="col2">
          <label for="form_phone">Phone <span class="required">*</span></label>
          <input type="tel" id="form_phone" name="form_phone" value="" required />
        </div>
        <div class="col12">
          <label for="form_attachment">Add Attachment</label>
          <input type="file" id="form_attachment" name="form_attachment" />
        </div>
        <div class="col12">
          <label for="form_message">Message <span class="required">*</span></label>
          <textarea id="form_message" name="form_message" required></textarea>
        </div>
        <div class="col12">
          <input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
        </div>
      </div>
<div id="contactSubmitResult"></div>

关于javascript - PHP、jQuery、Ajax、发送带有附件字段代码的 HTML 输入字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32659894/

相关文章:

javascript - 在第一个下拉列表中值有子元素,然后用户在第二个下拉列表中选择相同的值应该使用 jquery 接受

javascript - Vue 输入传递一个数组

php - 防止过多的数据库连接

jquery - 为什么我的 $.ajax 加载 - 然后取消?

php - 试图在一个简单的php系统中显示具有一对多关系的mysql数据?

php - 诡异的 MySQL 代码逻辑

javascript - 将一键事件绑定(bind)到三个不同的链接

javascript - 如何获取用作背景的图像的完整 URL?

javascript - 正则表达式 : how to limit max number of integers in an alphanumeric field

javascript - 使用 Canvas 以真实大小绘制图像