Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
    
I miss your homework. –  toscho Jan 4 '13 at 8:01

1 Answer 1

up vote 3 down vote accepted

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]

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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