如何提交AJAX表单仅特定字段



我有一个表单,允许用户更改他们的帐户信息。我添加了ajax请求以在不刷新页面的情况下保存更改。我的问题是,我不想提交表单上的所有字段,因为有些字段被禁用了。所以我只想发送一些字段。为了做到这一点,我在下面写了一个不起作用的代码,有人能帮我找出我错在哪里吗?

Functions.php

// Validate - my account
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']) == '') {
$response = wc_print_notices();
} else if ( isset( $_POST['account_first_name'] ) ) {
$response = wc_print_notices();
}
echo json_encode($response);
exit();
}

我的表单

<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' );?> > 

<!-- Message section -->
<div class="msg_box"></div>
<!-- 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代码
这就是我所做的,只发送特定字段,但不起作用。当点击提交按钮时,没有发生任何事情,也没有ajax请求。

jQuery(document).ready(function($) {

$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
// Specific form field
var $formData = {
name: $("#account_first_name").val(),
lastName: $("#account_last_name").val()
};
//Ajax Save settings
jQuery.ajax({
dataType: "json",
type: "POST",
data: formData,
success: function(data) {
jQuery('.newdiv').html(data);
}
});
});
});

这是Js代码,它发送表单的所有字段并正常工作

jQuery(document).ready(function($) {

$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Save settings
jQuery.ajax({
type: "POST",
data: jQuery(".mts-edit-account").serialize(),
success: function(data) {
jQuery('.newdiv').html(data);
}
});
});
});

您在这里遗漏了很多内容。

  1. 您正在使用WordPress ajax,因此您需要将在urlargs中使用的基于admin-ajax.php的url,但该url已丢失
  2. WordPress ajax需要表单数据中的action键和值,而这在您的代码中是缺失的
  3. WordPress还需要nonce,如果你在代码中提交nonce并进行nonce验证,那么这在代码中也是缺失的
  4. 您已经定义了dataType: 'json',这意味着您希望ajax响应中包含json,但在success函数中,您试图将json对象写入htmldiv,因此不清楚您在响应中实际发送了什么。您需要在这里工作,如果您发送html代码作为响应,则将使用dataType: 'html'。如果您发送json,则需要将html(data)更改为html(JSON.stringify(data)

因此,在更正了所有这些事情之后,您的代码应该是这样的,我已经提供了所有可能的解释,以便您能够理解我在代码中所做的和更改的内容。

注意:我还没有测试代码,所以如果你在控制台中看到任何错误,请告诉我,这样我就可以更新和修复代码

jQuery(document).ready(function ($) {
$(document).on('submit', '.mts-edit-account', function (e) {
// prevent default event.
e.preventDefault();
// define form element.
const form = $(this);
// get the wordpress ajax submission url from the form action attribute.
const ajax_url = form.attr('action');
// get specific form field using form.find().
var formData = {
first_name: form.find('#account_first_name').val(), // get first name.
last_name: form.find('#account_last_name').val(), // get last name.
action: form.find('input[name=action]').val(), // get the action value from the hidden field.
_wpnonce: form.find('input[name=save-account-details-nonce]'), // get the nonce value define by name save-account-details-nonce
/**
* NOTE: we're passing nonce by with key name _wpnonce
* so in you php code when you check for nonce validation
* use this key name not the save-account-details-nonce
* while the nonce action value is still save_account_details
*
* otherwise your nonce verification will show failed because you're not using correct key.
*/
};
$.ajax({
type: 'POST', // Request type is post
url: ajax_url, // set admin_url('admin-ajax.php') url here.
data: formData, // pass the form data with first_name, last_name, action, _wpnonce
dataType: 'json', // pass the return data type.
success: function (res) {
// if we have success in response.
if (res.success) {
const success_msg = res.data.message;
// now display this success message in your html element.
} else {
// when we get an error response.
// not our ajax is not failed here but we're error in success function
// because we're getting a response from ajax but error is in our php code.
// wp_send_json_error && wp_send_json_success do this thing
// you'll have to read about those functions
const error_msg = res.data.error;
// Now show this error message in your html element.
}
},
error: function () {
// catch the error.
console.log('Something not working!');
},
});
});
});

来谈谈处理ajax的PHP代码。add_action( 'woocommerce_save_account_details_errors', array( &$errors, &$user ), 1, 10 );我不确定您在这一行中添加了什么,当您有自己的ajax处理功能时,这没有任何意义。拆下这条线。

如果不能使用wc_print_notices(),则必须编写自己的验证和错误处理。要想使用wc_print_notices(),您需要深入了解WooCommerce。

此外,您还缺少验证、nonce检查、清理以及其他许多功能。你需要学习很多关于这些事情的知识。下面我准备了php代码,并试图解释基本原理,但如果你想了解这些函数及其用法,你需要在互联网或WordPress文档中搜索每个函数并了解它们。很难详细解释和教授所有这些功能以及它们是如何工作的。

注意:全局函数名称应始终使用前缀,以避免冲突并保持函数名称的唯一性。我已将save_account_details更改为vh_sto_wc_custom_save_account_details以使其独一无二。但是,您的nonce操作名称仍然是save_account_details,您可以更改它,并在以后的所有必需位置使其唯一

以下是用于处理ajax回调的php代码。

/**
* Ajax callback for saving account details.
*/
function vh_sto_wc_custom_save_account_details() {
// We are using try catch to handle the error and send in response.
// when validation fails.
try {
// Check if the nonce is available in post data.
if ( ! isset( $_POST['_wpnonce'] ){
throw new Exception( __( 'Nonce is missing.', 'your-text-domain' ) );
}
// validate the nonce.
if ( wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'save_account_details' ) ) {
throw new Exception( __( 'Nonce is invalid.', 'your-text-domain' ) );
}
// Check if the first name is available and not empty.
if ( ! isset( $_POST['first_name'] ) || empty( $_POST['first_name'] ) ) {
throw new Exception( __( 'First name should not be empty.', 'your-text-domain' ) );
}
// Check if the last name is available and not empty.
if ( ! isset( $_POST['last_name'] ) || empty( $_POST['last_name'] ) ) {
throw new Exception( __( 'Last name should not be empty.', 'your-text-domain' ) );
}
// Store values in array.
$first_name = sanitize_text_field( wp_unslash( $_POST['first_name'] ) );
$last_name  = sanitize_text_field( wp_unslash( $_POST['last_name'] ) );
// Get current user id.
$user_id = get_current_user_id();
// Check if the user id is a valid id.
if ( $user_id <= 0 ) {
throw new Exception( __( 'You are not allowed to perform this action.', 'your-text-domain' ) );
}
// update user data.
$user_data = wp_update_user(
array(
'ID'         => $user_id,
'first_name' => $first_name,
'last_name'  => $last_name,
)
);
// Check if there is any error on the update.
if ( is_wp_error( $user_data ) ) {
throw new Exception( __( 'Sorry, could not update your account details.', 'your-text-domain' ) );
} else {
// send success response when there is no error and the update was successful.
wp_send_json_success( array( 'message' => __( 'Your account details has been updated.', 'your-text-domain' ) ) );
}
} catch ( Exception $e ) {
// Send the error response with error message.
// in jquery you'll access by response.data.error
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
}
add_action( 'wp_ajax_save_account_details', 'vh_sto_wc_custom_save_account_details' );

您在PHP函数中提取的数据与提交的数据不同。

您已经在javascript中定义了name=account_first_name。因此,您的php函数正在查找$POST'account_first_name'字段,并为其提供name

因此,将您的ajax请求更改为:

jQuery(document).ready(function($) {

$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
// Specific form field
var formData = {
account_first_name: $("#account_first_name").val(),
account_last_name: $("#account_last_name").val()
};
//Ajax Save settings
jQuery.ajax({
type: "POST",
data: formData,
success: function(data) {
jQuery('.newdiv').html(data);
}
});
});
});

现在PHP函数得到了正确的字段。

好吧,要提交一些字段而不是其他字段,只需选择它们并在ajax主体中发送,类似于这样。

let id = $("SOMETHING").val();
let name =$("SomethingElse").val();
...etc

在ajax中执行

...,
data: {
id: id,
name: name,
...etc
},
...,

最新更新