简体   繁体   中英

How to handling validation with ajax request for woocommerce form

I am creating my custom form-edit-account.php template. This contains a form that allows users to change their name, surname, password and other info. Originally the form does not perform ajax requests, you click the save changes button, the data is saved and the page is reloaded. The required fields and their validity are managed by the file https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.218

What I did was create ajax request for the form in order to save the fields without the page refresh. The fields are edited and updated correctly, so it works. However, handling validation not working.

Somehow I need field handling validation but I don't know how to proceed I'm stuck at this point. I have two ideas I could work on:

  1. Try somehow to make the original handling validation work.

  2. Create a custom handling validation with js or php separately from the original file, but I don't know if this is correct.

How could I handle field validation? I hope someone can help me understand how I could do this, I appreciate any help and thank you for any replies.

Example of My-Form

<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> > 
  <!-- Fist & Last Name Field -->
  <div class="row name_surname">
    <div class="form-row">
      <label class="t3" for="account_first_name">Nome *</label>
      <input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
    </div>

    <div class="form-row">
      <label class="t3" for="account_last_name">Cognome *</label>
      <input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
    </div> 

    <!-- Save Settings -->
    <p style="margin-bottom: 0px!important;">
      <?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
      <button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
      <input type="hidden" name="action" value="save_account_details" />
    </p>
  </div>
</form>

Js File

jQuery(document).ready(function($) {
    
    $('.mts-edit-account').on('submit', function(e) { //form onsubmit ecent
        e.preventDefault(); // the preventDefault function stop default form action

    //Ajax function
    jQuery.ajax({
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
      url: "wp-admin/admin-ajax.php",
      success: function(data) {
        alert('Form Inviato');
      }
    });

    });

});

functions.php

add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
  // A default response holder, which will have data for sending back to our js file
  $response = array(
    'error' => false,
  );

  // Example for creating an response with error information (This not working)
  if (trim($_POST['account_first_name']) == '') {
    $response['error'] = true;
    $response['error_message'] = 'Name is required';

  if (trim($_POST['account_first_name']) == '') {
    $response['status'] = false;
    $response['message'] = 'Name is required';
    }else{
    $response['status'] = true;
    $response['message'] = 'success';
    }

    // Exit here, for not processing further because of the error
    echo json_encode($response);
    exit();
  }

  exit(json_encode($response));
}

Thanks to the intervention of Martin Mirchev in the comments I was able to solve the problem.Here is the solution for anyone who is in the same conditions.

(The form remained the same)

Js File

jQuery(document).ready(function($) {
    
    $('.mts-edit-account').on('submit', function(e) { 
        e.preventDefault(); 

    //Ajax function
    jQuery.ajax({
      
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
      url: "wp-admin/admin-ajax.php",
      success : function( response ) {
        //jQuery('.woocommerce-notices-wrapper').append(response);
        jQuery('.woocommerce-notices-wrapper').prepend(response);
      }

    });
    });
});

functions.php

add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {

  if (trim($_POST['account_first_name']) == '') {
    $response = wc_print_notices();
  } else {
    $response = "Settings Saved!";
  }

  // Don't forget to exit at the end of processing
  echo json_encode($response);
  exit();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM