[英]How to make this form do two things (AJAX and PHP mail) on submit?
這兩個表單提交功能都可以單獨工作,但如果我同時執行它們,則不能工作。
<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快。
如果您要同時執行請求和表單提交,則可以這樣完成:
$('#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
}
進行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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.