How to make this form do two things (AJAX and PHP

2019-07-29 07:45发布

问题:

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

回答1:

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
}


回答2:

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