如何使此表单在提交时做两件事(AJAX和PHP邮件)? [英] How to make this form do two things (AJAX and PHP mail) on submit?

查看:52
本文介绍了如何使此表单在提交时做两件事(AJAX和PHP邮件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Both of these form submission functions work individually but not if I have them both executing at the same time.

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

推荐答案

AJAX尚未完成,因为表单提交的速度比AJAX快.

The AJAX is not finished, because the form submission is faster than the AJAX.

如果您想同时执行请求和表单提交,则可以这样完成:

If you want to do both, the request and then the form submission, you can accomplish it like this:

$('#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:

The problem may be, that, if enable_post_data_reading is off in the php.ini file, the $_POST variable is not populated. To fix this, please try using php://input instead of $_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
}

这篇关于如何使此表单在提交时做两件事(AJAX和PHP邮件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆