Using Ajax to call a PHP function within a WordPress website

I am looking to trigger a PHP function using AJAX. Below is the code snippet of my form:

    <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>

I am interested in executing the following PHP function:

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';
    }  
}

How can I invoke a PHP function within WordPress using AJAX or JavaScript?

When attempting to execute the code, I receive an error message displayed in an alert box stating: "Request failed: undefined"

Incorporating PHP, HTML, and JavaScript with AJAX confuses me. Can someone please guide me on where I may have gone wrong?

Answer №1

Here is the code snippet to add in your function.php file:

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';
    } 
}

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Executing follow-up tasks using multiple partial views in MVC3 on ASP.NET

Although this question may have been asked before, I am seeking guidance on how to approach implementing a specific scenario. In my ASP.NET MVC3 controller, I need to create a view that includes multiple partial views, each interacting with the database fo ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

The keyup event fails to trigger for the search input in datatables when ajax is being used

When loading a page with a jQuery datatable via AJAX, I am aiming to implement custom filtering when the user starts typing in the default filter provided by datatables. The custom logic needs to be applied when the keyup event is triggered. Since AJAX is ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Performing AJAX requests within AJAX requests without specifying a callback function for success

Upon reviewing this discussion jQuery Ajax Request inside Ajax Request Hello everyone, I'm in need of some clarification on a particular scenario. I recently took over the code from a former member of my development team and noticed that they have ma ...

Alternative solution to avoid conflicts with variable names in JavaScript, besides using an iframe

I am currently using the Classy library for object-oriented programming in JavaScript. In my code, I have implemented a class that handles canvas operations on a specific DIV element. However, due to some difficulties in certain parts of the code, I had t ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Mastering web authentication using android studio

https://i.stack.imgur.com/g1jpd.png My server provides JSON data to my android app. How can I bypass the authentication code for username and password in Android Studio when the website requires authentication? I want users of my mobile app to avoid havi ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class. Currently, when I am on the Home Page, the list item for Account Co ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

The Ajax form is failing to retrieve the expected PHP data

My login system uses a combination of ajax and php. The form validation is handled through javascript, with the form data then being sent to php for database checks. In the past, this method has worked well for me, but in this instance, it seems 'NOTH ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Combining two elements in a React application

Having a collection of assets and their quantities: const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 }; const assetList = { eth: { name: "Ethereum", icon: "urlhere", colour: "#030", text: "light&q ...

Tips for achieving a blurred background image effect when hovering, while keeping the text unaffected

Hey there, I've recently started my journey into web development and have encountered a roadblock. I'm trying to blur the background image of a div on hover without affecting the text inside. I have an id called c1 where I used a javascript func ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...