I am building my personal website based on wordpress / woocomerce. I am currently working on a form that allows users to change their account information such as name, surname and much more. Everything seems to be working fine.
What I'm trying to do now is make the form work with ajax requests without the need to refresh the page. I think I am on the right track but I have some small difficulties.
Currently, when the form is submitted the page is not loaded, so I have reached the goal, however the ajax request generates the error 400 and I don't understand why.
I apologize if this is a trivial question but I am new to all of this.
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>
Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
$.post($form.attr('action'), $form.serialize(), function(data) {
alert('This is data returned from the server ' + data);
}, 'json');
});
});
functions.php
add_action( 'wp_ajax_custom_action', 'save_account_details' );
add_action( 'wp_ajax_nopriv_custom_action', 'save_account_details' );
function custom_action() {
$response = array(
'error' => false,
);
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Name is required';
exit(json_encode($response));
}
exit(json_encode($response));
}