0

guys. I've tried to build a wordpress simple registration form with ajax, but it doesn't work at all. Here is my code, a php and jQuery ajax. Please tell me what's wrong with my code.

FYI, (1) the 'alert' didn't work, (2) the data didn't entered into my custom table, (3) I added 'e.preventDefault()' and 'return false' in 'my-test-reg.js' but it doesn't avoid resubmsission form when I reload the browser.

// The .php function code

if (!defined('ABSPATH')) { exit; }
add_action( 'wp_enqueue_scripts', 'load_scripts' );

// Load scripts
function load_scripts()
{
    // I called jquery.min.js and jquery validation from function.php, not from here

    wp_enqueue_script('test-reg', get_template_directory_uri() . '/js/my-test-reg.js', array('jquery'), '1.0', true ); 

    wp_localize_script( 'test-reg', 'myAjax', array(
        'myUrl' => admin_url('admin-ajax.php')
        ) 
    );

    add_action( 'wp_ajax_nopriv_add_to_register', 'to_register' );
}

function to_register()
{
    $nonce = $_REQUEST['nonce'];

    if ( empty( $_POST) || !wp_verify_nonce( $nonce, 'my-nonce') )
    {
        die('Oopss...');
    } else {
        global $wpdb;

        $firstName = sanitize_text_field( $_POST['firstName)'] );
        $lastName  = sanitize_text_field( $_POST['lastName)'] );
        $email     = sanitize_email( $_POST['email'] );

        $custom_table = $wpdb->prefix . "my_custom_table";
        $the_email = $wpdb->get_row( "SELECT `email` FROM $table_name" );

        if ( $the_email == $email )
        {
            $res['type'] = 'error';
            $res['show'] = '<span> The e-mail you entered already exists</span>';

            $res = json_encode($res);
            echo $res;

            die();
        } else {
            $entered = $wpdb->insert ($custom_table, 
                array(
                    'firstName' => $firstName, 
                    'lastName' => $lastName, 
                    'email' => $email
                ), 
                array(
                    '%s', 
                    '%s', 
                    '%s'
                ) 
            );
        }

        if ( $entered )
        {
            $res['type'] = 'success';
            $res['show'] = '<span> Hello, you\'re success! </span>';

            $res = json_encode($res);
            echo $res;

            die();
        }
    }
}

function reg_form()
{
    $nonce = wp_create_nonce('nonce');

    $out = '<form id="test-register" method="post">';
    $out = '<div id="response"></div>';
    $out = '<input type="text" name="firstName" id="your-firstName" required>';
    $out .= '<input type="text" name="lastName" id="your-lastName" required>';
    $out .= '<input type="text" name="email" id="your-email" required>';
    $out .= '<input type="submit" id="submit-btn" value="Go">
            <input type="hidden" id="my-nonce" value="'.$nonce.'">';
    $out = '</form>';

    return $out;
}


// Here is my code of 'my-test-reg.js'
jQuery(document).ready(function($) {
    var formIsValid = $('#test-register');

    formIsValid.validate();

    $('#test-register').submit(function(e) {
        e.preventDefault();

        // Get the data
        var mydata = {
            action: 'add_to_register',
            firstName: $(this).find('#your-firstName').val();
            lastName: $(this).find('#your-lastName').val();
            email: $(this).find('#your-email').val();
        };

        // Call the ajax
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: myAjax.myUrl,
            data: mydata,
            success: function ( response )
            {
                if ( response.type == 'success' )
                {
                    alert( 'Congrat, you are success!' ); // Doesn't work
                    $( '#response' ).html();  // Doesn't work
                } else {
                    alert( 'Not Success!' );  // Doesn't work
                    $( '#response' ).html();  // Doesn't work
                }
            }
        });

        return false;
    });
});

Hopefully anyone would help me.

Best regards

1 Answer 1

0

Move this action ' add_action( 'wp_ajax_nopriv_add_to_register', 'to_register' );' from load_scripts function().

// Load scripts
function load_scripts()
{
    // I called jquery.min.js and jquery validation from function.php, not from here

    wp_enqueue_script('test-reg', get_template_directory_uri() . '/js/my-test-reg.js', array('jquery'), '1.0', true ); 

    wp_localize_script( 'test-reg', 'myAjax', array(
        'myUrl' => admin_url('admin-ajax.php')
        ) 
    );


}
add_action( 'wp_ajax_nopriv_add_to_register', 'to_register' );

Replace reg_form() function with following:-

function reg_form()
{
    $nonce = wp_create_nonce('nonce');

$out = '<form id="test-register" method="post">';
$out .= '<div id="response"></div>';
$out .= '<input type="text" name="firstName" id="your-firstName" required>';
$out .= '<input type="text" name="lastName" id="your-lastName" required>';
$out .= '<input type="text" name="email" id="your-email" required>';
$out .= '<input type="submit" id="submit-btn" value="Go">
        <input type="hidden" id="my-nonce" value="'.$nonce.'">';
$out .= '</form>';

return $out;
}

You haven't concatenated the $out variable.

3
  • Ok, I did. But nothing happens as before.
    – life4learn
    May 30, 2015 at 10:58
  • Try to defined '$res = array()' in to_register() first then add type and show to $res.
    – Domain
    May 30, 2015 at 11:08
  • Nothing happens. I try to make it simple by changing this if ( empty( $_POST) || !wp_verify_nonce( $nonce, 'my-nonce')) { die('Oopss...') } else { echo "Horay"; }. By this checking, neither 'Oopss' and 'Horay' showed up. I think something wrong with the form, but I can't figure it.
    – life4learn
    May 30, 2015 at 14:36

Your Answer

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

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