Вызовите функцию PHP, используя ajax в WordPress. - PullRequest
0 голосов
/ 05 января 2020

Я хочу вызвать функцию php, используя ajax. Вот мой код формы

    <form class="woocommerce-form woocommerce-form-login login" method="post">
    <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="reg_billing_name"><?php esc_html_e( 'Full Name', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="reg_billing_name" id="reg_billing_name" autocomplete="reg_billing_name" value="<?php echo ( ! empty( $_POST['reg_billing_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_billing_name'] ) ) : ''; ?>" />
    </p>

    <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="reg_billing_email"><?php esc_html_e( 'Email Address', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="email" class="woocommerce-Input woocommerce-Input--text input-text" name="reg_billing_email" id="reg_billing_email" autocomplete="reg_billing_email" value="<?php echo ( ! empty( $_POST['reg_billing_email'] ) ) ? esc_attr( wp_unslash( $_POST['reg_billing_email'] ) ) : ''; ?>" />
    </p> 

    <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="reg_billing_phone"><?php esc_html_e( 'Mobile Number', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="tel" class="woocommerce-Input woocommerce-Input--text input-text" name="reg_billing_phone" id="reg_billing_phone" autocomplete="reg_billing_phone" value="<?php echo ( ! empty( $_POST['reg_billing_phone'] ) ) ? esc_attr( wp_unslash( $_POST['reg_billing_phone'] ) ) : ''; ?>" />
    </p> 
    <button type="submit" class="woocommerce-Button button" onclick="customerregister();"><?php esc_html_e( 'Register', 'woocommerce' ); ?></button>
    </form>

<script>
 function customerregister() {
            $.ajax({
            url: "<?php echo get_home_url(); ?>/wp-admin/admin-ajax.php",
            type: 'POST',
            dataType: 'JSON',
            data: {
                action: 'devsol_customer_auth_register'
            },
            success: function(data, status, xhr){
                console.log(data)
                if(data.data == 'success')
                    window.location = 'http://localhost/final/my-account'
                else
                    alert("Error: No account found with this Mobile number. Please register now and get 10% Discount coupon.")

            },
            error: function (xhr, ajaxOptions, thrownError) {
                // this error case means that the ajax call, itself, failed, e.g., a syntax error
                // in your_function()
                alert ('Request failed: ' + thrownError.message) ;
            },
        })
     }       
</script>

Я хочу вызвать эту php функцию

function devsol_customer_auth_register() {
    $customer_name = sanitize_text_field( $_POST['reg_billing_name'] );
    $customer_phone = sanitize_text_field( $_POST['reg_billing_phone'] );
    $customer_email = sanitize_email( $_POST['reg_billing_email'] );    
    $customer_password = wp_generate_password( 12, true );       

if ( !username_exists($customer_phone) && !email_exists($customer_email) ) {       
        $user_id = wp_create_user($customer_phone, $customer_password, $customer_email);                                 
        if ( !is_wp_error( $user_id ) ) {   

        wp_clear_auth_cookie();
        wp_set_current_user ( $user_id );
        wp_set_auth_cookie  ( $user_id );

        wp_update_user(array( 
            'ID' => $user_id,
            'first_name' => $customer_name,
            'role' => 'customer', ));      
        }      
    }   
    else {
        echo 'Account already existed';
    }  
}

Как я могу вызвать php функцию в WordPress, используя ajax или javascript ,

Я получаю сообщение об ошибке в окне предупреждения, и ошибка: Запрос не выполнен: undefined

Я добавил php, html и javascript ajax, в моем вопросе кто-то, пожалуйста, помогите мне, что я сделал не так?

1 Ответ

1 голос
/ 06 января 2020

Вставьте этот код в вашу функцию. php

add_action( 'wp_ajax_devsol_customer_auth_register', 'devsol_customer_auth_register' );
add_action( 'wp_ajax_nopriv_devsol_customer_auth_register', 'devsol_customer_auth_register' );


function devsol_customer_auth_register() {

    $customer_name = sanitize_text_field( $_REQUEST['reg_billing_name'] );
    $customer_phone = sanitize_text_field( $_REQUEST['reg_billing_phone'] );
    $customer_email = sanitize_email( $_REQUEST['reg_billing_email'] );    
    $customer_password = wp_generate_password( 12, true );       

    if ( !username_exists($customer_phone) && !email_exists($customer_email) ) {       
            $user_id = wp_create_user($customer_phone, $customer_password, $customer_email);                                 
            if ( !is_wp_error( $user_id ) ) {   

            wp_clear_auth_cookie();
            wp_set_current_user ( $user_id );
            wp_set_auth_cookie  ( $user_id );

            wp_update_user(array( 
                'ID' => $user_id,
                'first_name' => $customer_name,
                'role' => 'customer', ));      
            } 
            $user = new WP_User( $user_id );
            $user->set_role( 'customer' );
            wp_mail( $customer_email, 'New User Registration', 'Your Password: ' . $customer_password );     
        }   
    else {
        echo 'Account already existed';
    } 
}

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...