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

Jak*_*ake 1 javascript php forms jquery

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

<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); 
     }
?> 
Run Code Online (Sandbox Code Playgroud)

Luc*_*bel 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
            }
      });      
    }); 
Run Code Online (Sandbox Code Playgroud)

回答OP的评论:

问题可能是,如果enable_post_data_reading在php.ini文件中关闭,$_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
}
Run Code Online (Sandbox Code Playgroud)