简体   繁体   中英

How to handle ajax errors on response.

I have a single page order form. The user fills our the form, javascript validates everything and if it passes an ajax request will hit the server and charge the customer via Stripe when they click submit.

If the charge is successful, json is returned to the ajax request ( {success:true} ). The user is then redirected to an success page, or an error is displayed if something happened when charging the card.

I'm trying to handle a (rare) issue where the user's request hits the server, the user is successfully charged, but on response the user receives an error (most likely a timeout error on mobile/unstable connection). How can I prevent a user from being double charged? Below is my ajax request, but maybe I need to rethink my entire infrastructure?

$.ajax({ type : 'POST',
url      : '/order',
data     : $(':input').serialize(),
timeout  : 30000,
dataType : 'json',
success : function (data) {

  // redirect user to success page
  window.location = '/completed';

},
error: function(xhr,status,error) {

  // report the error to user. 

} });

Try this..

$.ajaxSetup({ 
type     : 'POST',
url      : '/order',
data     : $(':input').serialize(),
timeout  : 30000,
dataType : 'json',
success : function (data) {

  // redirect user to success page
  window.location = '/completed';

},
error: function(xhr,status,error) {

  if (xhr.status == 408) {//For Timeout
                alert("Sorry, Request timeout.!");
                window.location.href ="//specify a redirect url//";
            }
            else {
                alert("An error occurred: " + status + "nError: " + error);
            }

} });

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