Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript PHP、jQuery、Ajax、发送带有附件字段代码的HTML输入字段不起作用_Javascript_Php_Jquery_Html_Ajax - Fatal编程技术网

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

Javascript PHP、jQuery、Ajax、发送带有附件字段代码的HTML输入字段不起作用,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我正在尝试发送一封带有可选附件的电子邮件,单击按钮并在表单字段上方显示结果。我已经编写了以下代码,但它不起作用(当我单击submit按钮时没有发生任何事情;我想创建一个fiddle,但JSFIDLE不接受PHP代码): 以下是HTML: <div id="contactSubmitResult"></div> <div id="contactSubmitResult"></div> <div id="contact

我正在尝试发送一封带有可选附件的电子邮件,单击按钮并在表单字段上方显示结果。我已经编写了以下代码,但它不起作用(当我单击submit按钮时没有发生任何事情;我想创建一个fiddle,但JSFIDLE不接受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>

$(文档).ready(函数(){
matchFormFields=“#contactForm输入[必需],#contactForm文本区域[必需]”;
matchContactSubmitResult=“#contactSubmitResult”;
errorColor='红色';
$(“#表单_发送”)。单击(函数(){
var formIsValid=真;
//循环遍历每个字段,并将无效字段的边框颜色更改为红色
$(matchFormFields)。每个(函数(){
$(this.css('border-color','');
//检查字段是否为空
if(!$.trim($(this.val())){
$(this.css('border-color',errorColor);
formIsValid=false;
}
//检查电子邮件是否有效
var email\u reg=/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this.attr(“type”)==“email”&&!email注册测试($.trim($(this.val())){
$(this.css('border-color',errorColor);
formIsValid=false;
}   
});
//如果表单字段内容有效,则向服务器提交数据
if(formIsValid){
//检索要发送到服务器的输入字段值
var post_data=新表单数据();
post_data.append('form_firstname',$).val();
post_data.append('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]。文件[0]);
post_data.append('form_message',$).val();
//Ajax将数据发布到服务器
$.ajax({
网址:'http://jdoe.com/sendContactFormEmail.php',
数据:post_数据,
contentType:false,
processData:false,
键入:“POST”,
数据类型:“json”,
成功:功能(响应){
if(response.type=='error'){//从服务器加载json数据并输出消息
输出=“”+response.text+“”;
}否则{
输出=“”+response.text+“”;
//重置所有表单字段中的值
$(matchFormFields).val(“”);
}
//显示带有表单提交结果的动画
$(matchContactSubmitResult.hide().html(output.slideDown());
}
});
}
});
//在表单字段中输入字符时重置边框
$(matchFormFields).keyup(函数(){
$(this.css('border-color','');
$(matchContactSubmitResult.slideUp();
});
});
以下是接收jQuery AJAX POST请求的PHP代码:

<?php

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

      //die($output);

  include("settings.php");

  $boundaryString = "generateboundaryfromthis";

  $to_email = "jdoe@gmail.com";

  $from_email = "noreply@jdoe.com";

  $replyTo_email = "noreply@jdoe.com";

  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);

    }

  }
“错误”,
'text'=>'应为Ajax POST请求。'
));
模具(产量)//输出json数据的退出脚本
} 
//检索经过消毒的输入数据
$form\u firstname=filter\u var($\u POST[“form\u firstname”],filter\u SANITIZE\u STRING);
$form\u lastname=filter\u var($\u POST[“form\u lastname”],filter\u SANITIZE\u STRING);
$form\u address=filter\u var($\u POST[“form\u address”],filter\u SANITIZE\u STRING);
$form\u city=filter\u var($\u POST[“form\u city”],filter\u SANITIZE\u字符串);
$form\u email=filter\u var($\u POST[“form\u email”],filter\u SANITIZE\u email);
$form\u phone=filter\u var($\u POST[“form\u phone”],filter\u SANITIZE\u NUMBER\u INT);
$form\u message=filter\u var($\u POST[“form\u message”],filter\u SANITIZE\u STRING);
$email_body=getContents(“mailSentSuccess”);
$output=json_编码(数组('type'=>'message','text'=>'messagesent');
模具(产量);
}否则{
//$output=json_encode(数组('type'=>'error','text'=>$pageSettings->getContents(“mailSentFailure”));
$output=json_encode(数组('type'=>'error','text'=>'遇到错误。消息未发送');
模具(产量);
}
}

一个问题:您忘记将html标记放在

matchContactSubmitResult = "#contactSubmitResult";


名字*
姓氏*
地址
城市
电子邮件*
电话*
添加附件
信息*

我已经更新了我的代码。PHP代码没有错误,但是当我 尝试附加附件—不会发生任何情况

如果是这样,我认为问题就在这里。尚未测试,但这可能会有所帮助:)


由于我使用jQuery和AJAX来完成这篇文章,所以没有,而是有一个封闭的。我在网上看到过,应该是有效的HTML。我不是在陈词滥调。我正在使用jQuery动态提交。在我添加附件代码之前,我的代码是在一个封装中工作的,所以我不确定问题出在哪里
<div id="contactSubmitResult"></div>
var myfile=$('input[name=form_attachment]').val();
//apend the file
post_data.append('form_attachment', myfile);