简体   繁体   中英

How to load payment success message without reloading page

I'm using a custom stripe payment form to process a payment. The payment and everything goes through all good but my problem is that the page is reloading and then displaying the success message. I'd like to incorporate some type of jquery ajax if possible but my method doesn't seem work. It still just reloads.

Here is the breakdown of my code. All the code is located on the same page but I'll breakdown the main areas below.

FORM:

<form action="" method="POST" id="payment-form" class="form-horizontal">


  <div class="username-info">
    <input type="text" name="name" maxlength="70" placeholder="Your full name" class="name form-control" value="Test Name">
  </div>

  <div class="email-info">
    <input type="text" name="email" maxlength="65" placeholder="Email address" class="email form-control" value="testemail@email.com">
  </div>

  <div class="password-info">
    <input type="password" name="password" maxlength="70" placeholder="Password (min 6 characters)" class="password form-control" value="password123">
  </div>

  <div class="form-row">
    <label>
      <span>Card Number</span>
      <input type="text" size="20" data-stripe="number">
    </label>
  </div>

  <div class="form-row">
    <label>
      <span>Expiration (MM/YY)</span>
      <input type="text" size="2" data-stripe="exp_month">
    </label>
    <span> / </span>
    <input type="text" size="2" data-stripe="exp_year">
  </div>

  <div class="form-row">
    <label>
      <span>CVC</span>
      <input type="text" size="4" data-stripe="cvc">
    </label>
  </div>

</form

Javascript:

<script type="text/javascript">
            // this identifies your website in the createToken call below
            Stripe.setPublishableKey('test_key_goes_here');

            function stripeResponseHandler(status, response) {
                if (response.error) {
                    // re-enable the submit button
                    $('.submit-button').removeAttr("disabled");
                    // show hidden div
                    document.getElementById('a_x200').style.display = 'block';
                    // show the errors on the form
                    $(".payment-errors").html(response.error.message);
                } else {
                    var form$ = $("#payment-form");
                    // token contains id, last4, and card type
                    var token = response['id'];
                    var posted = document.getElementById("post-price").value
                    // insert the token into the form so it gets submitted to the server
                    form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
                    form$.append("<input type='hidden' name='posted' value='" + posted + "' />");
                    // and submit
                    form$.get(0).submit();
                }
            }
</script>

PHP:

<?php
require 'lib/Stripe.php';

$error = '';
$success = '';

if ($_POST) {
Stripe::setApiKey("test_key_goes_here");

try {
if (empty($_POST['name']) || empty($_POST['password']) || empty($_POST['email']))
    throw new Exception("Fill out all required fields.");
  if (!isset($_POST['stripeToken']))
    throw new Exception("The Stripe Token was not generated correctly");
  Stripe_Charge::create(array("amount" => $_POST['posted'],
                              "currency" => "cad",
                              "card" => $_POST['stripeToken'],
             "description" => $_POST['email']));
  $success = '<div class="alert alert-success">
              <strong>Success!</strong> Your payment was successful.
     </div>';
}
catch (Exception $e) {
$error = '<div class="alert alert-danger">
     <strong>Error!</strong> '.$e->getMessage().'
     </div>';
}
}
?>



<div class="alert alert-danger" id="a_x200" style="display: none;"> <strong>Error!</strong> <span class="payment-errors"></span> </div>
<span class="payment-success">
<?= $success ?>
<?= $error ?>
</span>

Also here is the jquery ajax request I was trying :

Updated to include URL

  $("#payment-form").submit(function(e) {

      e.preventDefault();
      var url = "pricing.php";  

      $.ajax({
             type: "POST",
             url: url,
             data: $("#payment-form").serialize(),
             success: function(data)
             {
                 alert(data);
             }
           });

  });

It is failing because you do not have an url attribute for your ajax call.

For example:

var url = "your url here";
$.ajax({
    "dataType": "json",
    "type": "POST",
    "url": url,
    "data": params,
    "success": function (result) {
         // Your Logic HERE
    },
    "fail": function ShowFail(xhr) { alert("Sorry! Failed"); },
    "error": function (request, status, error) {
        alert('Error=' + error + ' & Status=' + status);
    }

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