如何在ajax成功后重定向到另一个页面

时间:2016-01-23 04:49:29

标签: javascript php jquery ajax

下面我有一个ajax请求,如果成功的话,可以重定向到另一个页面,但即使没有任何错误,也无法让它重定向。我已经在这里工作了10个小时,非常感谢任何帮助

            var $form = $('#payment-form');

            function showErrorDialogWithMessage(message){
                $('#payment-error').removeClass('hidden').addClass('error').append(message);
            }

            function stripeResponseHandler(status, response){
                if (response.error) 
                {
                    // Stripe.js failed to generate a token. The error message will explain why.
                    // Usually, it's because the customer mistyped their card info.
                    // You should customize this to present the message in a pretty manner:
                    $('#payment-error').removeClass('hidden').addClass('error').append(response.error.message); //Throw relevant error
                } 
                else 
                {   
                    // Stripe.js generated a token successfully. We're ready to charge the card!
                    var token = response.id;
                    $form.append($('<input type="hidden" name="stripeToken" />').val(token));

                    // Make the call to the server-script to process the order.
                    // Pass the token and non-sensitive form information.
                    var request = $.ajax({ //Process the form using $.ajax()
                        type        : 'POST', //Method type
                        url         : 'charge.php', //Your form processing file url
                        dataType    : 'json',
                        data        : $form.serialize(), //serialize form
                        success     : function(data) {
                            if(data.success == true){
                                window.location.replace("http://weloveapp.co.uk/portal/push.php");
                            }
                        }
                    });
                }
            }

            jQuery( document ).ready(function($) {

                $form.submit(function(event) { //Trigger on form submit
                    $('.error').empty(); //Clear the messages first

                    var emailAddress = $('.emailAddress').val();
                    var name = $('.name').val();
                    var cardNumber = $('.creditnumber').val();
                    var cardCVC = $('.creditcvc').val();

                    // Validate the email address:
                    var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

                    if (emailAddress === "") {
                        showErrorDialogWithMessage("Please enter your email address.");
                    } else if (!emailFilter.test(emailAddress)) {
                        showErrorDialogWithMessage("Your email address is not valid.");
                    }

                    if (name === "") {
                        showErrorDialogWithMessage("Please enter your name.");
                    }

                    // Stripe will validate the card number and CVC for us, so just make sure they're not blank
                    if (cardNumber === "") {
                        showErrorDialogWithMessage("Please enter your card number.");
                    }
                    if (cardCVC === "") {
                        showErrorDialogWithMessage("Please enter your card security code.");
                    }


                    // createToken returns immediately - the supplied callback submits the form if there are no errors
                    Stripe.createToken({
                        number: $('.creditnumber').val(),
                        cvc: $('.creditcvc').val(),
                        exp_month: $('.creditexpiremonth').val(),
                        exp_year: $('.creditexpireyear').val()
                    }, stripeResponseHandler);

                    event.preventDefault(); //Prevent the default submit
                });

            });

                <?php
            require_once('stripe-payment/init.php');
            require_once('../wp-config.php');
            global $wpdb;

            $errors  = array();     // array to hold validation errors
            $form_data = array();       // array to pass back data

            $adminemail = 'hello@weloveapp.com';

            $emailAddress = $_POST['emailAddress'];
            $name = $_POST['name'];
            $creditnumber = $_POST['creditnumber'];
            $creditcvc = $_POST['creditcvc'];
            $creditexpiremonth = $_POST['creditexpiremonth'];
            $creditexpireyear = $_POST['creditexpireyear'];

            if(!$emailAddress){
                $errors['emailAddress'] = 'Please enter an email';
            }
            elseif(!$name){
                $errors['name'] = 'Please enter your name';
            }
            elseif(!$creditnumber){
                $errors['creditnumber'] = 'Please enter credit card number';
            }
            elseif(!$creditcvc){
                $errors['creditcvc'] = 'Please enter cvc';
            }
            elseif(!$creditexpiremonth){
                $errors['creditexpiremonth'] = 'Please enter expire month';
            }
            elseif(!$creditexpireyear){
                $errors['creditexpireyear'] = 'Please enter expire year';
            }

            // if there are any errors in our errors array, return a success boolean of false
            if (!empty($errors)) {

                // if there are items in our errors array, return those errors
                $form_data['success'] = false;
                $form_data['errors']  = $errors;
            } else {

                try {
                    \Stripe\Stripe::setApiKey('sk_test_CdOuItKDV4I42DFK4ehTg9Xo');
                    // $myCard = array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2016);
                    $myCard = array('number' => $_POST['cardnumber'], 'exp_month' => $_POST['creditexpiremonth'], 'exp_year' => $_POST['creditexpireyear']);
                    $token = htmlspecialchars($_POST['stripeToken']);
                    $total_amount = '3.99';
                    $total_amount = $total_amount*100;

                    $charge = \Stripe\Charge::create(array(
                    'amount' => $total_amount, 
                    'currency' => 'GBP', 
                    'card' => $token
                    ));

                    //setcookie($cookie_name, $cookie_value, time()+86400); // 86400 = 1 day                        

                    $ipaddress = $_SERVER['REMOTE_ADDR'];


                    $result = $wpdb->get_var( "SELECT ip FROM push WHERE ip='$ipaddress'");


                    if($result == $ipaddress){
                        $wpdb->update( 'push', 
                            array( 'date' => date('Y-m-d')  ),
                            array( 'ip' => $ipaddress ), 
                            array( '%s' )               
                        );

                    } else {
                        $wpdb->insert( 'push', array(
                            'ip' => $cookie_name, 
                            'date' => date('Y-m-d'),
                            'status' => $cookie_value ),
                            array( '%s', '%s', '%s' ) 
                        );
                    }


                    $msg="Hello ".$name.","
                                . "<br> <br>We have received the payment, you can now access push notifications."
                                . "<br> Thanks,";

                    $headers = 'From: We Love APP <hello@weloveapp.co.uk>' . "\r\n" .
                    'Reply-To: hello@weloveapp.com' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();

                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "content-type: text/html\r\n";

                    mail($emailAddress, 'Payment successful', $msg, $headers);

                    $msg="Hello Admin,"
                                . "<br> <br>You have received a new payment for push notifications"
                                . "<br> Thanks,";

                    $headers = 'From: New Push Notification Payment' . "\r\n" .
                    'Reply-To: ' .$emailAddress.' ' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();

                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "content-type: text/html\r\n";

                    mail($adminemail, 'You have received a new payment for push notifications', $msg, $headers);

                    // show a message of success and provide a true success variable
                    $form_data['success'] = true;
                    $form_data['posted']='We have received your payment.';  
                }
                catch(Exception $e){
                    $errors['key']='danger';
                    $errors['msg'] = $e->getMessage();

                    $form_data['success'] = false;
                    $form_data['errors']  = $errors;
                }
            }
            // return all our data to an AJAX call
            echo json_encode($form_data);
            ?>

2 个答案:

答案 0 :(得分:-1)

最好使用一些整数值来检查truefalse。尝试使用

'1' instead of `true` and '0' instead of `false` 

PHPAJAX

答案 1 :(得分:-1)

删除dataType: 'json';,然后在测试data.success之前需要执行data = JSON.parse(data),这样做我觉得它应该有用。