You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于WP REST API的Ajax用户注册表单故障排查求助

Let's break down the issues with your registration implementation and fix them step by step.

1. Fix the HTML Form Syntax Error

Your address input field has incomplete syntax that breaks the form structure. Here's the corrected version:

<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="address"><?php _e( 'Store address', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="address" id="address" value="<?php echo ( ! empty( $_POST['address'] ) ) ? esc_attr( $_POST['address'] ) : ''; ?>" />
</p>

The original code cut off mid-way when setting the value attribute — this fixes that and ensures valid HTML.

2. Fix Critical Issues in the Ajax Script

Your jQuery code has several blockers preventing the registration from working. Let's address each one:

a. Prevent Default Form Submission

Without stopping the browser's default form submit behavior, the page will reload and interrupt your Ajax request. Add e.preventDefault() at the start of the submit handler.

b. Define the Missing data Variable

You're referencing a data variable that doesn't exist. Use $(this).serialize() to collect form data in the same application/x-www-form-urlencoded format your Ionic app uses.

c. Fix the Duplicate API URL Segment

Your URL has a redundant wp-json (wp-json/wp-json/sow/v1/regist_user/), which will return a 404 error. Remove the duplicate to get the correct endpoint path.

d. Use the Correct Error Callback Name

jQuery Ajax uses error (not failure) for its error handling callback.

e. Ensure Nonce is Properly Passed

You need to populate the JP_POST_EDITOR global variable in WordPress using wp_localize_script to pass the valid REST API nonce and messages. Add this to your theme's functions.php or a custom plugin:

function enqueue_registration_scripts() {
    wp_enqueue_script( 'registration-script', get_template_directory_uri() . '/js/registration.js', array( 'jquery' ), '1.0', true );
    
    // Pass nonce and localization messages to the frontend
    wp_localize_script( 'registration-script', 'JP_POST_EDITOR', array(
        'nonce' => wp_create_nonce( 'wp_rest' ), // Use the standard WP REST nonce
        'successMessage' => __( 'Registration successful!', 'woocommerce' ),
        'failureMessage' => __( 'Registration failed. Please try again.', 'woocommerce' )
    ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_registration_scripts' );

3. Final Working Ajax Script

Here's the fully corrected jQuery code:

(function( $ ){
    $( document ).ready(function() {
        $( 'form' ).on( 'submit', function(e) {
            // Stop the browser from reloading the page
            e.preventDefault();
            
            var $form = $(this);
            var formData = $form.serialize();
            
            $.ajax({
                type: "POST",
                url: 'https://url/wp-json/sow/v1/regist_user/', // Fixed URL
                dataType: 'json',
                data: formData,
                contentType: 'application/x-www-form-urlencoded', // Match Ionic's content type
                beforeSend: function( xhr ) {
                    xhr.setRequestHeader( 'X-WP-Nonce', JP_POST_EDITOR.nonce );
                },
                success: function(response) {
                    alert( JP_POST_EDITOR.successMessage );
                    $( "#results").append( JSON.stringify( response ) );
                    // Optional: Reset the form after successful registration
                    $form[0].reset();
                },
                error: function( jqXHR, textStatus, errorThrown ) {
                    alert( `${JP_POST_EDITOR.failureMessage} Error: ${errorThrown}` );
                    // Log detailed error for debugging
                    console.log( 'API Error Response:', jqXHR.responseText );
                }
            });
        });
    });
})( jQuery );

4. Verify Your REST API Endpoint

Double-check that your sow/v1/regist_user/ endpoint is correctly registered in WordPress, accepts POST requests, and validates/sanitizes all input fields (first_name, last_name, username, address). It should also execute the Google Maps geocoding logic you already built for the Ionic app.

For debugging, test the endpoint directly with tools like Postman first to confirm it works before relying on the frontend form.

内容的提问来源于stack exchange,提问作者Lorenzo Varano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:28:44