Search code examples
htmljqueryajaxwordpress

Not displaying ajax alert


I'm trying to have a login form in wordpress as a plugin But I have a problem with ajax that is about not display alert and I think older version of wordpress was diffrent because I learned it from a old video that was about wordpress developing

ajax code

jQuery(document).reday(function ($) {

    $('#loginForm').on('submit', function (event) {

        event.preventDefault();
        let user_email = $('#userEmail').val();
        let user_password = $('#userPassword').val();
        let notify = $('.alert');
        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'post',
            datatype: 'json',
            data: {
                action: 'app_auth_login',
                user_email: user_email,
                user_password: user_password

        },
        success: function (response) {},
        error: function (error) {
            if (error) {
                notify.addClass('alert-error');
                notify.append('<p>there is an error</P>');
                notify.css('display','block');
            }
        }
    });

 });

});


login form

<div class="auth-wrapper">
    <div class="alert" style="display:none;">

    </div>
    <div class="login-wrapper" method="post" id="loginForm">
        <form action="">

            <div class="form-row">
                <label for="userEmail">ایمیل :</label>
                <input type="text" name="userEmail" id="userEmail"></input>
            </div>
            <div class="form-row">
                <label for="userPassword">کلمه عبور :</label>
                <input type="text" name="userPassword" id="userPassword"></input>
            </div>
            <div class="form-row">
                <button name="submitLogin">ورود</button>
            </div>

        </form>

    </div>

</div>

function that register the js

<?php


function app_auth_load_assets()
{

    wp_register_style('app_auth_style', APP_AUTH_URL . 'assets/css/auth.css');
    wp_enqueue_style('app_auth_style');

    wp_register_style('app_auth_script', APP_AUTH_URL . 'assets/js/auth.js', ['jquery']);
    wp_enqueue_style('app_auth_script');

}

add_action('wp_enqueue_scripts', 'app_auth_load_assets');

and I'm using shortcode for that

<?php


function app_auth_login_handler($atts, $content = null)
{
    include APP_AUTH_TPL . "front/login.php";
}

function app_auth_register_handler($atts, $content = null)
{
    include APP_AUTH_TPL . "front/register.php";
}

add_shortcode('app_auth_login', 'app_auth_login_handler');
add_shortcode('app_auth_register', 'app_auth_register_handler');

Solution

  • Issues and Fixes AJAX Script Error: Your jQuery code has a typo: jQuery(document).reday should be jQuery(document).ready. Also, datatype should be dataType.

    Form Handling: Your loginForm has the method="post" attribute, but it should be in the tag, not the tag.

    Enqueueing JavaScript: You should use wp_enqueue_script instead of wp_enqueue_style to include your JavaScript file. Also, make sure to use wp_localize_script to pass AJAX URL and any localized data to your JavaScript file.

    Handling AJAX Request: Ensure you have a handler in your WordPress functions.php or plugin file to process the AJAX request.

    jQuery(document).ready(function ($) {
    
        $('#loginForm').on('submit', function (event) {
            event.preventDefault();
            
            let user_email = $('#userEmail').val();
            let user_password = $('#userPassword').val();
            let notify = $('.alert');
    
            $.ajax({
                url: ajaxurl, // 'ajaxurl' is provided by WordPress
                type: 'post',
                dataType: 'json',
                data: {
                    action: 'app_auth_login',
                    user_email: user_email,
                    user_password: user_password
                },
                success: function (response) {
                    if (response.success) {
                        notify.removeClass('alert-error').addClass('alert-success').text('Login successful').show();
                    } else {
                        notify.removeClass('alert-success').addClass('alert-error').text(response.data.message).show();
                    }
                },
                error: function () {
                    notify.removeClass('alert-success').addClass('alert-error').text('There was an error').show();
                }
            });
    
        });
    
    });  
    

    In the plugin :

    function app_auth_load_assets()
    {
        wp_register_style('app_auth_style', APP_AUTH_URL . 'assets/css/auth.css');
        wp_enqueue_style('app_auth_style');
    
        wp_register_script('app_auth_script', APP_AUTH_URL . 'assets/js/auth.js', ['jquery'], null, true);
        wp_enqueue_script('app_auth_script');
        
        // Make sure to localize script to pass AJAX URL
        wp_localize_script('app_auth_script', 'app_auth_vars', [
            'ajax_url' => admin_url('admin-ajax.php')
        ]);
    }
    
    add_action('wp_enqueue_scripts', 'app_auth_load_assets');
    
    function app_auth_login()
    {
        // Check nonce for security
        // if ( !isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'app_auth_nonce') ) {
        //    wp_send_json_error(['message' => 'Invalid nonce']);
        //    return;
        // }
    
        // Retrieve email and password from AJAX request
        $email = sanitize_email($_POST['user_email']);
        $password = sanitize_text_field($_POST['user_password']);
        
        $user = wp_authenticate($email, $password);
        
        if (is_wp_error($user)) {
            wp_send_json_error(['message' => $user->get_error_message()]);
        } else {
            wp_set_auth_cookie($user->ID);
            wp_send_json_success();
        }
    }
    
    add_action('wp_ajax_app_auth_login', 'app_auth_login');
    add_action('wp_ajax_nopriv_app_auth_login', 'app_auth_login');
    

    Explanation JavaScript Changes:

    Changed jQuery(document).reday to jQuery(document).ready. Corrected datatype to dataType. Used ajaxurl for the AJAX request URL, which is automatically provided by WordPress when you localize your script. Enqueue Scripts:

    Used wp_enqueue_script for JavaScript and wp_localize_script to pass the AJAX URL to your script. PHP Handler:

    Added error checking and user authentication. Used wp_send_json_success() and wp_send_json_error() for proper AJAX response handling. With these changes, your AJAX login form should work correctly, providing feedback to the user based on the success or failure of the login attempt.