duankeng1911 2017-01-24 14:54
浏览 65
已采纳

在调用PHP函数的AJAX请求之后,在表单提交时重定向页面

I have an HTML page (index.html) that collects an email address and submits it to a server via an AJAX POST request. When the submit button is clicked, a javascript function executes the post request via AJAX and then the page submits to itself. I need to modify this so that the page submits to another page (thankyou.html) instead of to itself. I'm not sure how to do this in PHP. Is there a way to redirect a PHP page once a form is submitted and the AJAX query is executed?

I'm not sure if I should redirect the page in Javascript or in HTML or in PHP.

This is the form in index.html:

       <form class="email-form" method="POST" validate>
            <div class="email-input-container register-info-email">
                <input class="email-input" type="email" autocapitalize="off" autocorrect="off" autocomplete="off" required name="MERGE0" id="MERGE0" placeholder="Email Address" pattern="[a-z0-9._%+-]+@[a-z0-9-]+\.[a-z]{2,63}$" aria-label="Email Address">
                <input id="sub-button" type="submit" class="submit-button" value="Submit" >
                <span class="success-message"><span class="sr-only">We got you</span></span>
            </div>
        </form>

This is the post request in PHP (post.php)

if ( isset($_POST['email']) ) :

    $data = [
            'email' => $_POST['email']
    ];

    if ( isset($_POST['platform']) ) :

            $data["device"] = $_POST['platform'];

    endif;

    syncMailchimp($data);

endif;

This is the AJAX request:

        $.ajax({
            type: "POST",
            url: 'post.php',
            data: data,
            success: function(data, status) {

                var message = JSON.parse(data).message;

                if (message == "error") {

                    $('.email-form small').html('An error has occurred. Please try submitting again.');
                    smallHighlight();

                } else if (message == "subscribed") {

                    $('.email-form small').html('You are already subscribed');
                    smallHighlight();

                } else {

                    $('.email-form').addClass('form-success');
                    $('.email-form small').attr('style', '');

                }

            },
  • 写回答

2条回答 默认 最新

  • duancha1065 2017-01-24 14:59
    关注

    If you want to redirect to another page, put this after form is successfully submited

    window.location = "http://www.example.com/thankyou.html";
    

    EDIT: You shouldn't handle this redirect in PHP, because this is asynchronous call. You need to reference this somehow in you submit script

    Hope it helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?