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" 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 >
<div >
<label for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div >
<label for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" 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" 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));
}
CodePudding user response:
Maybe I found a solution to submit data with the form using ajax request but I'm not sure. As I am a newbie I hope someone can correct or improve my answer below. Anyway, now the data is sent and saved correctly but I still have some problems which I list below.
After sending I get 302 (redirect) status
If one of the fields is empty the validate does not work, the form is submitted anyway, while an error message should appear.
Context: I'm working with woocommerce, so my form belongs to the form-edit-account.php template. This allows users to change their account settings such as first name, last name and much more.
Reference: I followed this tutorial which helped me tremendously - https://regularcoder.com/submit-form-using-ajax-in-wordpress/
My Form
<form name="Form" 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 >
<div >
<label for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div >
<label for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" 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" 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 Js
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' );
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, to know in our js file
// about the error and behave accordingly, like adding error message to the form with JS
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Email is required';
if (trim($_POST['account_first_name']) == '') {
$response['status'] = false;
$response['message'] = 'Email is required';
}else{
$response['status'] = true;
$response['message'] = 'success';
}
// Exit here, for not processing further because of the error
echo json_encode($response);
exit();
}
// ... Do some code here, like storing inputs to the database, but don't forget to properly sanitize input data!
// Don't forget to exit at the end of processing
exit(json_encode($response));
}