简体   繁体   中英

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.

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.

I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.

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

Please refer on the codes. Can someone help me how to figure this out.

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

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

$('#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;
        })
    });

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