0

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.

3
  • 3
    The header function only redirects the ajax call (making the ajax call result in content from the header redirect). You will want to instead return like a json object, that ajax will use to then do the redirect inside the success callback. Commented Jun 25, 2020 at 13:59
  • 2
    Why not redirect using window.location on Ajax Form Success from JS? Commented Jun 25, 2020 at 14:00
  • You must do the redirect in your JavaScript. Commented Jun 25, 2020 at 14:15

1 Answer 1

2

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;
        })
    });
Sign up to request clarification or add additional context in comments.

3 Comments

I did it but its pass the fullname validation and directly shows success message without really submitting data.
Then u need to handle session, once a account created, made a session and once your page called with action=joined, it should have the info of session of that account. In fact u need to show the code where u are handling GET request of register.php
You have to include the window.location.href in the done function, as mentioned here. @Ulrich As per this answer, once the ajax call is successful, it would redirect the page with the window.location and subsequently your success message will show on new page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.