简体   繁体   中英

How to make this form do two things (AJAX and PHP mail) on submit?

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

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

Answering to the OP's comment:

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
}

Do a SUBMIT chained to the onclick event.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM