1

How to create the custom login/Registration form using AJAX.

1
  • 3
    I miss your homework.
    – fuxia
    Commented Jan 4, 2013 at 8:01

1 Answer 1

6

Here is a simple shortcode that gets the job done:

add_shortcode('ajax_login','ajaxlogin_shortcode_handler');
function ajaxlogin_shortcode_handler($atts,$content=null){
    if (is_user_logged_in())
        return;

    $retval = '<p id="message" style="color:red"></p>'
            .wp_login_form(array('form_id' => 'ajaxloginform','echo' => false)).
            '<div id="login-result" style="position:absolute; top:300px; left: 670px;">
                <img src="path/ajax-loader.gif"/>
            </div>';

    $js = <<<JS
<script type="text/javascript">
    jQuery(document).ready(function($){
        $("#ajaxloginform").click(function() {
            // turn loading screen on
            $('#login-result').toggle();
            //get foem data
            var input_data = $('#my-login-form').serialize();
            //make ajax call
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('wp-login.php','login_post'); ?>",
                data: input_data,
                success: function(msg) {
                    // if login incorrect, wordpress will redirect user to its own login form. We scan for an error term.
                    var reg1 = /login_error/g;
                    if (reg1.test(msg)) {
                        $('#message').html("<?php _e('Your login credentials is not correct. Please try again.'); ?>");
                    }else {
                        // login success. redirect users to some page.
                        //$(location).attr('href', '/my-account/');
                        //or reload the same page
                        location.reload();
                    }
                }
            });
            // turn loading screen off
            $('#login-result').toggle();
            // prevent actual submission of form
            return false;
        });
    });
</script>
JS;
    //enqueue jquery if its not already loaded
    wp_enqueue_script('jquery');
    return $retval .$js;
}

Usage:

[ajax_login]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.