Submitting post to database then redirecting to paypal

Not sure how I ran into this question one year later, but since it is unanswered…

Instead of self-submitting the form and then redirecting to Paypal, you can instead have the paypal url as your form’s action, but use Ajax to save the form data before the form is submitted to Paypal. You can also use the Ajax response to prepare the form before submission, e.g. filling some hidden fields

Here’s an example:

myform.php:

<form id="myform" method="post" action="<?php echo $paypal_url; ?>">
   <input type="text" ...>
   <input type="hidden" name="my-hidden-field" id="my-hidden-field" value="this is hidden"> 
   ...other form fields...
</form>

saveform.php: Processes the Ajax request and returns a response that can be used to manipulate the form before submission

<?php 
  if (!empty($_POST)) {
     //save $_POST data to the database
     ...
     //also, fill some data as response
     $response = array('my_hidden_field' => 'this is now filled in');
     //next line returns the response
     echo json_encode($response);  
  }

myform.js: Submits form data to saveform.php before submitting to paypal

$j = jQuery.noConflict();

$j(document).ready(function() {
    $j('#myform').submit(submit_myform);
});

function submit_myform() {
    if (!myform_is_valid()) {
        window.location.href = "#myform"; 
        return false;//prevent normal browser submission, to display validation errors
    } else {
        $j.ajax({
           url: 'saveform.php',
           type: 'POST',
           data: $j(this).serialize(),
           dataType:'json', //data type of Ajax response expected from server
           success: myform_success //callback to handle Ajax response and submit to Paypal
        });
       return false;//prevent normal browser submission, since the form is submitted in the callback
   } 
}

function myform_is_valid() {
    $valid = true;
    //validate data; if there's a validation error, set $valid=false and display errors on page
    ...
    return $valid;
}

function myform_success(response) {
    //this is called whenever the ajax request returns a "200 Ok" http header
    //manipulate the form as you wish
    $j('#my-hidden-field').val(response.my_hidden_field);
    //submit the form (to the form's action attribute, i.e $paypal_url)
    document.forms['myform'].submit(); 
}

Instead of the jquery.ajax call you can also use the shorter:

$j.post('saveform.php',$j('#myform').serialize(),myform_success,"json")

Leave a Comment