Home > database >  Ajax request not save form data when add woocommerce hook
Ajax request not save form data when add woocommerce hook

Time:09-15

I customized the form-edit-account.php template by adding ajax requests to save data without page refresh. It works fine, the data is saved correctly. The problem occurs when the hook woocommerce_save_account_details_errors is added. This hook allows to view error messages when form fields are not respected, or view success messages if all fields are fine. Why does adding that hook break the save form data?

In functions.php
I have this function which allows me to save data. However, if I add add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 ); for message display, data saving does not work.

add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
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();

}

Js at the end of the form

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 save settings
    jQuery.ajax({
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
      url: "wp-admin/admin-ajax.php",
      success: function(data) {
        $('.woocommerce-notices-wrapper').html(data);
      }
    });

  });

});

CodePudding user response:

I found a solution, we needed to add array with var to the hook &$errors &$user

add_action( 'woocommerce_save_account_details_errors', array( &$errors, &$user ), 1, 10 );

add_action( 'wp_ajax_save_account_details', 'save_account_details' );

function save_account_details( $user_id ) {
  if (trim($_POST['account_first_name']) == '') {
      wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
      $response = wc_print_notices();
    } else if ( isset( $_POST['account_first_name'] ) ) {
      wc_add_notice("Modifiche salvate con successo", "success");
      $response = wc_print_notices();
    }
    echo json_encode($response);
    exit();
}
  • Related