I'm editing the form-edit-account.php template. This template contains a form that allows users to change account settings (name, surname, age etc ..). Originally the form had no ajax requests, so I added them to save data without page refresh. Everything works fine but I have some doubts about how I could refine the code.
When click on submit button of my form, in google console network tab I see that there are two requests, one belongs to Ajax Handling Error, while the other belongs to Ajax Save settings.
Ajax Handling Error allows me to view messages when form fields are not respected or success messages if all goes well.
Ajax save settings actually saves the data without reloading the page.
What I would like to do is get a single request (saves settings and shows error messages). It's possible merge ajax hanling error code and ajax save settings code in a single request instead of two ?
Js at the end of the form
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
$.post($form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json');
//Ajax Save settings
jQuery.ajax({
type: "POST",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
});
});
});
functions.php
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']) == '') {
wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else{
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}
CodePudding user response:
I found a solution, I don't know how right it can be, I'm just a fan and not a programmer. With this solution I only see a request in google console network card. Also everything works fine, the data is saved and the messages are ok. I post the solution below for anyone who is in the same situation as me.
I just changed the script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json'
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});