如何使这个表单提交两件事(AJAX和PHP邮件)?

时间:2018-04-10 19:22:44

标签: javascript php jquery forms

这两个表单提交功能都可单独工作,但如果我同时执行它们则不会。

<form action=""  method="post" id="timesheet" >
   <input type="submit" name="submit" value="Submit" id="submit" />
</form> 


<script>
 //first, post results to a Google Spreadsheet 
  $('#submit').on('click', function(e) {
     var jqxhr = $.ajax({
            url: url,  //google sheet URL
            method: "GET",
            dataType: "json",
            data : $form.serializeArray()
      });      
    }); 
</script>  


<?php
  // then email the user their response
      if(isset($_POST["submit"])){

     // standard PHP mail function (some code left out)
        $subject = "WORK TIMESHEET SUBMITTED";
        mail($email, $subject, $message, $headers); 
     }
?> 

2 个答案:

答案 0 :(得分:7)

AJAX尚未完成,因为表单提交比AJAX更快。

如果您想要同时执行请求,然后是表单提交,您可以像这样完成:

$('#submit').on('click', function(e) {
     e.preventDefault(); // prevent form submission
     var jqxhr = $.ajax({
            url: url,  //google sheet URL
            method: "GET",
            dataType: "json",
            data : $form.serializeArray(),
            success: () => {
                $("#timesheet").submit(); // submit the form when the ajax is done
            }
      });      
    }); 

回答OP的评论:

问题可能是,如果php.ini文件中的enable_post_data_reading关闭,则不会填充$_POST变量。要解决此问题,请尝试使用php://input代替$_POST

$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$submit = $response["submit"];

if ($submit) {
    // Your Logic for creating the email
}

答案 1 :(得分:1)

将一个SUBMIT链接到onclick事件。

//first, post results to a Google Spreadsheet 
$('#submit').on('click', function(e) {
 var jqxhr = $.ajax({
        url: url,  //google sheet URL
        method: "GET",
        dataType: "json",
        data : $form.serializeArray()
  });
//Then, chain a submit!
}).submit();