简体   繁体   English

使用 PHP 和 Ajax 重新加载和重定向页面

[英]Page reload and redirect using PHP and Ajax

I have a registration form using php, I'm checking the inputs with a validations and control the submitting form using ajax.我有一个使用 php 的注册表单,我正在使用验证检查输入并使用 ajax 控制提交表单。

Everything works fine, except, after clicking submit button, Ajax loads the success result, in same registration form, and also not reload the page and redirect.一切正常,除了点击提交按钮后,Ajax 在相同的注册表单中加载成功结果,也不会重新加载页面和重定向。

I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.我想重新加载并重定向register.php页面进行register.php?action=joined using Ajax 表单提交。

Before Ajax register.php have its own statement, if the registration succsessful ( $_GET['action'] == 'joined' )* its redirect and destroy the registration form and show success form.*在Ajax注册之前。php有自己的声明,如果注册成功$_GET['action'] == 'joined' )*它的重定向和销毁注册表并显示成功表。*

Please refer on the codes.请参考代码。 Can someone help me how to figure this out.有人可以帮我解决这个问题。

registercontrol.php寄存器控制.php

<?php

if(isset($_POST['fullname'])){
    //fullname validation
    $fullname = $_POST['fullname'];

    if (! $user->isValidFullname($fullname)){
        $infofn = 'Your name must be alphabetical characters';      
        echo '<p>'.$infofn.'</p>';
    }       
}

// If form has been submitted process it
if(isset($_POST['submit']) && $_POST['submit'] == 'register')
{   

    // Create the activasion code
    $activasion = md5(uniqid(rand(),true));
    
    try 
    {

        // Insert into database with a prepared statement
        $stmt = $db->prepare('INSERT INTO members (fullname) VALUES (:fullname, :email, :active)');
        $stmt->execute(array(
            ':fullname' => $fullname,           
            ':email' => $email,
            ':active' => $activasion
        ));
        $id = $db->lastInsertId('memberID');

        // Send email
        $to = $_POST['email'];
        $subject = "Verify Your Account";
        $body = "<p>Thank you for registering on the demo site.</p>
        <p>Hello ".$fullname.", Please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";

        $mail = new Mail();
        $mail->setFrom(SITEEMAIL);
        $mail->addAddress($to);
        $mail->subject($subject);
        $mail->body($body);
        $mail->send();

        // Redirect to index page
        header('Location: register.php?action=joined');
        exit;

    // Else catch the exception and show the error.
    } 
    catch(PDOException $e) 
    {
        $error[] = $e->getMessage();
    }   
}
?>

register.php and ajax validations register.php 和 ajax 验证

<script type="text/javascript">
    $(document).ready(function() {

        $("#fullname").keyup(function(event) {
            event.preventDefault();
            var fullname = $(this).val().trim();
            if(fullname.length >= 1) {
                $.ajax({
                    url: 'registercontrol.php',
                    type: 'POST',
                    data: {fullname:fullname},
                    success: function(response) {
                    // Show response
                    $("#vfullname").html(response);
                    }
                });
            } else {
                $("#vfullname").html("");
            }
        });     

        $('#submit').click(function(event) {
            event.preventDefault();
            var formData = $('#register-form').serialize();
            console.log(formData);
            $.ajax({
                url: 'registercontrol.php',
                method: 'post',
                data: formData + '&submit=register'
            }).done(function(result) {
                $('.hidden').show();
                $('#result').html(result);              
            })
        });                 

    });
</script>

<?php
    // If action is joined show sucesss
    if(isset($_GET['action']) && $_GET['action'] == 'joined')
    {                               
        echo '<div>
                <p>Registration is successful, please check your email to activate your account.</p>                                                
                </div>';                                    
    } 
    else 
    { ?>
        <div>
            <h1>Create an Account!</h1>                                 
        </div>
        <form id="register-form" role="form" method="post" 
        action="registercontrol.php" autocomplete="off">                                
                                            
        <input type="text" name="fullname" id="fullname" placeholder="Your name" value="" required>                                     
        <div id="vfullname"></div>                      
        <input type="email" name="email" id="email" placeholder="Your Email" value="" required>
                                                                
        <input id="submit" type="submit" name="submit" value="Create Account">

        <p class="hidden">Please check everything.</p>                              
        <div id="result"></div>
    </form>
<?php } ?>

Thank you.谢谢你。

Check the done block and perform your redirect with JavaScript:检查done块并使用 JavaScript 执行重定向:

$('#submit').click(function(event){
        event.preventDefault();
        var formData = $('#register-form').serialize();
        console.log(formData);
        $.ajax({
            url: 'registercontrol.php',
            method: 'post',
            data: formData + '&submit=register'
        }).done(function(result){
            var url_to_redirect = "register.php?action=joined";
            window.location.href = url_to_redirect;
        })
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM