-2

I'm trying to load the Stripe payment gateway. For some reason the page always refreshes before showing the response. I don't want the page refresh though.

This is the 'js' that I'm working with (a mix of 'jQuery' and vanilla js)

<script type="text/javascript">
            // this identifies your website in the createToken call below
            Stripe.setPublishableKey('stripe_key_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    

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

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

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

                    });

                }
            }
</script>

Got the form code here as well:

<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>


  <button class="btn btn-success pricing-display-pay" id="post-price" value="300" type="submit">Pay $</button>

</form
eabates
  • 878
  • 1
  • 8
  • 22
StackUnderFlow
  • 339
  • 1
  • 11
  • 36
  • Remove `get(0)`, however your logic is a little odd. Not least of all because of the flicking back and forth between jQuery and POJS. – Rory McCrossan Nov 04 '16 at 20:50
  • It's a little confusing, you have an event handler inside that function, and that function looks like something that would run on a form submit anyway, so why is the event handler there. Also, you're using the native `submit()`, not jQuery's version of `submit()`, which can cause some issues. – adeneo Nov 04 '16 at 20:50
  • Use a typical form.submit or use AJAX. Don't use both. – Scott Marcus Nov 04 '16 at 20:51
  • Show us your HTML form. – Nandan Bhat Nov 04 '16 at 20:52
  • @StackUnderFlow Don't use a submit button at the bottom of your form. Then you can remove `$("#payment-form").get(0).submit(...`. Instead, just use a regular button and wire its click event up to your AJAX call. – Scott Marcus Nov 04 '16 at 21:01

2 Answers2

0

I wrote a similar update without refreshing function. Comparing yours with mine, I suggest instead of:

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

Try:

 $('#payment-form').on('submit', function (e) {

My relevant html is:

 <input type="submit" value="submit" name="submit"/>

in a form.

Person
  • 11
  • 2
  • It is counter intuitive to have a submit button that invokes a submit event that will always be cancelled. It causes more code to have to be written and (as this example shows) more opportunities for errors. See my comment to the OP for the correct way to solve the issue. – Scott Marcus Nov 04 '16 at 21:02
-2

If your form is submitted by an <input type="submit"/> button, you need to return false at the end of your javascript to overload default behaviour.

Kevin Grosgojat
  • 1,386
  • 8
  • 13
  • If you don't want the form to actually submit, you should just use a `button` and set up it's `click` event. – Scott Marcus Nov 04 '16 at 20:50
  • In the code showed in the question we don't know the html structure of his form and on wich event the function is binded. That's why i talk about this. – Kevin Grosgojat Nov 04 '16 at 20:52
  • Doesn't matter. If you want AJAX to control your data submission (and we do know that the OP wants that), then you don't want a form to submit. Especially since the OP tells us that the page is refreshing. That doesn't happen with an AJAX call - it would happen with a form.submit. – Scott Marcus Nov 04 '16 at 20:54
  • You can easily use the form.submit event to post your form with ajax. If you use this method, and doesn't return false, your web page will refresh, because it's the behaviour of html form ... – Kevin Grosgojat Nov 04 '16 at 20:56
  • Apparently, it's not so easy, is it? As I said to Person (above), this technique is counter intuitive, requires more code and is prone to errors. Also, returning false is not the correct way to prevent native event behavior. The correct way is `event.preventDefault()` followed by `event.stopPropagation()`. – Scott Marcus Nov 04 '16 at 21:04
  • It's easy, i've build many ajax forms with that. Conserning return false vs e.preventDefault() & e.stopPropagation() in Jquey context is the same, at the difference of number of code lines. Read this : http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Kevin Grosgojat Nov 04 '16 at 21:12
  • You are missing the point. You may have done it, but that doesn't make it the correct pattern, use best-practices or follow standards. This technique is tantamount to a forced `goto`. – Scott Marcus Nov 04 '16 at 21:15
  • Ok, can you give me an official link that approve than binding a submit event on a form and prevent normal behaviour with a return false isn't the best practice ? – Kevin Grosgojat Nov 04 '16 at 21:18
  • No. Can you give me an official link that proves that picking something up and immediately putting it down doesn't waste time? You can argue this point all you want, but there is no denying that your technique requires more code, is counter-intuitive and is error prone. Can you prove me wrong on any one of those points? Do you think that such a pattern would be a best-practice? Or, would a best-practice be to use less (more readable) code that directly addresses the problem? – Scott Marcus Nov 04 '16 at 21:21
  • Ok, so following your standard and your patterns, it's not a good practice. I am reassured. That doesn't make my answer wrong. If you can't justify your opinion by official ECMA or JQuery link to approve your purpose, you can't say that it doesn't respect standards. Personnally i don't know the Scott Marcus standard, sorry, i just try to find ways to help community ;-) – Kevin Grosgojat Nov 04 '16 at 21:28
  • You can get defensive if you wish, but I am simply trying to help you. Using `return false` in a jQuery context has two problems with it. 1) It's easy to confuse it with plain JS `return false` and 2) Knowing what that one instruction actually does may not be clear. Lastly, I would just say that I have been teaching jQuery and JavaScript (as well as C#, VB, XML, VBA, HTML & CSS) for 20 years and can tell you without a doubt that just because something *can* be done in jQuery does not mean that it is *best* done in jQuery. Often jQuery is the wrong choice for an operation. – Scott Marcus Nov 04 '16 at 21:33
  • Lastly, if you wish to write excessive code that is unclear as to its purpose and is prone to causing errors, that's your business, but I don't think you can put up any plausible argument for writing such code. – Scott Marcus Nov 04 '16 at 21:36
  • Read this link, one more time please. http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false You can teach JQuery or what you want it doesn't matter, I'm a Javascript software developper too and i dont need to justify my purpose telling you what i'm doing IRL (and i teached javascript and jQuery too :O). In a jQuery context, return false is correct. Not in native JS but this is not the point. Solutions to solve problems can be different, and correct. In my point of view, confusion risks are not an available argument because they depends on personal habits. – Kevin Grosgojat Nov 04 '16 at 21:44
  • Using form.submit event instead of button.click allow you to overide the default form behaviour. I think it's the best thing to do here because he just want to do customed actions on form.submit event. As JQuery defines itself as a 'write less do more library', i really think it's better to overload default comportement and used the JQuery allowed 'return false' instruction IN THAT CASE. I wish you good luck too ;-) – Kevin Grosgojat Nov 04 '16 at 22:34