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.

I created a register template for Wordpress with some ajax so that users can click on the register link in my header and the register form opens up in a lightbox. For some reason on submit, if there is an error or success message my form gets displayed twice. Any help appreciated. I am confused because I have almost identical code for my login page with no issues. Here is the code:

<?php
/**
* Template Name: Register
*/

/* Load registration file. */
require_once( ABSPATH . WPINC . '/registration.php' );

/* Check if users can register. */
$registration = get_option( 'users_can_register' );

/* If user registered, input info. */
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'adduser' ) {
$user_pass = wp_generate_password();
$userdata = array(
    'user_pass' => $user_pass,
    'user_login' => esc_attr( $_POST['user_name'] ),
    'first_name' => esc_attr( $_POST['first_name'] ),
    'last_name' => esc_attr( $_POST['last_name'] ),
    'nickname' => esc_attr( $_POST['nickname'] ),
    'user_email' => esc_attr( $_POST['email'] ),
    'user_url' => esc_attr( $_POST['website'] ),
    'aim' => esc_attr( $_POST['aim'] ),
    'yim' => esc_attr( $_POST['yim'] ),
    'jabber' => esc_attr( $_POST['jabber'] ),
    'description' => esc_attr( $_POST['description'] ),
    'role' => get_option( 'default_role' ),
);

if ( !$userdata['user_login'] )
    $error = '<span>A username is required for registration.</span>';
elseif ( username_exists($userdata['user_login']) )
    $error = '<span>Sorry, that username already exists!</span>';
elseif ( !is_email($userdata['user_email'], true) )
    $error = '<span>You must enter a valid email address.</span>';
elseif ( email_exists($userdata['user_email']) )
    $error = '<span>Sorry, that email is already registered!</span>';
elseif ( !$userdata['first_name'] )
    $error = '<span>Please kindly enter your First Name.</span>';
elseif ( !$userdata['last_name'] )
    $error = '<span>Please kindly enter your Last Name.</span>';

else {
    $new_user = wp_insert_user( $userdata );
    wp_new_user_notification($new_user, $user_pass);
    echo '<div id="result" style="color:#FF0000">Thank you for Registering!<br/>Please check your email address. That\'s where you\'ll recieve your login password.<br/> (It might go into your spam folder)</div>';
}

 }

?>

<!-- REGISTER FORM STARTS HERE -->

<?php if (!$new_user) { ?>

        <div id="error" style="color:#FF0000"><?php echo $error; ?></div>
        <div id="result" style="color:#FF0000"></div>

        <form method="post" id="adduser" class="user-forms" action="<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>">

            <p class="form-username">
                <label for="user_name"><?php _e('Email Address *', 'frontendprofile'); ?></label>
                <input class="text-input" name="user_name" type="text" id="user_name" value="<?php if ( $error ) echo wp_specialchars( $_POST['user_name'], 1 ); ?>" />
            </p><!-- .form-username -->

            <p class="first_name">
                <label for="first_name"><?php _e('First Name', 'frontendprofile'); ?></label>
                <input class="text-input" name="first_name" type="text" id="first_name" value="<?php if ( $error ) echo wp_specialchars( $_POST['first_name'], 1 ); ?>" />
            </p><!-- .first_name -->

            <p class="last_name">
                <label for="last_name"><?php _e('Last Name', 'frontendprofile'); ?></label>
                <input class="text-input" name="last_name" type="text" id="last_name" value="<?php if ( $error ) echo wp_specialchars( $_POST['last_name'], 1 ); ?>" />
            </p><!-- .last_name -->

            <p class="form-email" style="display:none">
                <label for="email"><?php _e('E-mail *', 'frontendprofile'); ?></label>
                <input class="text-input" name="email" type="hidden" id="email" value="<?php if ( $error ) echo wp_specialchars( $_POST['email'], 1 ); ?>" />
            </p><!-- .form-email -->

            <p class="form-submit">
                <?php echo $referer; ?>
                <input name="adduser" type="submit" id="addusersub" class="submit button" value="Register" />
                <?php wp_nonce_field( 'add-user' ) ?>
                <input name="action" type="hidden" id="action" value="adduser" />
            </p><!-- .form-submit -->

        </form><!-- #adduser -->

        <script type="text/javascript">
        //Username = Email on Register
        jQuery("#user_name").change(function(){
            $("#email").val($(this).val());
        });

        //Ajax for Error Messages
        jQuery("#addusersub").click(function() 
        {
            jQuery('#result').html('Loading ...').fadeIn();
            var input_data = $('#adduser').serialize();
            $.ajax({
                type: "POST",
                url:  "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>",
                data: input_data,
                success: function(data){
                    $('#result').html(data);
                }
            }); return false;
        });
        </script>


<?php }  ?>

<!-- REGISTER FORM ENDS HERE -->
share|improve this question
    
Close-voted as off-topic. This is an HTML/AJAX question, not a WordPress question. –  Chip Bennett Apr 11 '12 at 12:03
add comment

1 Answer

up vote 1 down vote accepted

Your form is displaying twice because you are handling your AJAX wrong, and using the template that shows the form as the response too. You need to wrap the form code in an if else statement that checks if there is an AJAX request currently in operation.

But more obviously, you're going about AJAX completely the wrong way. WordPress has a nice pretty documented API that will let you take all that code out of your template and put it somewhere else ( and reduce the amount of code ).

See here for how: http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

e.g.

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

function myajax_submit() {
    // get the submitted parameters
    $postID = $_POST['postID'];

    // generate the response
    $response = json_encode( array( 'message' => 'why hello there javascript, Im doing fine thankyou' ) );

    // response output
    header( "Content-Type: application/json" );
    echo $response;

    // IMPORTANT: don't forget to "exit"
    exit;
}

javascript:

jQuery.post(
    // see tip #1 for how we declare global javascript variables
    MyAjax.ajaxurl,
    {
        // here we declare the parameters to send along with the request
        // this means the following action hooks will be fired:
        // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
        action : 'myajax-submit',

        // other parameters can be added along with "action"
        message : 'hello wordpress this is javascript, how are you?'
    },
    function( response ) {
        alert( response );
    }
);

Doing it this way separates your form code from your AJAX registration logic, making the issue you described near impossible.

Also look at the mention of jquery-form in that article I linked to, which simplifies things even further.

For brownie points, when using the WordPress AJAX API, WordPress defines the constant DOING_AJAX to let you know that you're in the middle of an AJAX call. Use this to skip things and add other things in that may be important

if(defined('DOING_AJAX')){
    // AJAX only stuff...
share|improve this answer
    
Thanks for the help Tom. I have managed to fix the code and the ajax is now working however I will have a read of the article to see how I can improve on my code. The article is not for the feint hearted. –  uknowit2 Apr 12 '12 at 12:01
    
it's quite clear, and fundamentally there is nothing hard or complex about the WP AJAX apis, figuring out how many '../'s to put in the include statement usually consumes far more time, but it's not the only source of information on this. You should be able to get quite far by simply copy pasting the AJAX code it gives and modifying it –  Tom J Nowell Apr 12 '12 at 12:28
add comment

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.