Hii我正在尝试使用javascript、AJAX和php将表单数据保存到用户元数据表中。这是我的密码
HTML表单:
<form id="savem" method="post">
<input type="text" name="profile_name" id="profile_name"/>
<input type="text" name="value1" id="value1"/>
<input type="text" name="value2" id="value2"/>
<input type="submit" value="save"/>
</form>
将脚本排入函数队列。php
function save_measurment() {
$theme_url = get_template_directory_uri(); // Used to keep our Template Directory URL
$ajax_url = admin_url( \'admin-ajax.php\' ); // Localized AJAX URL
// Register Our Script for Localization
wp_register_script(
\'measurment\', // Our Custom Handle
"{$theme_url}/assets/js/measurment.js", // Script URL, this script is located for me in `theme-name/scripts/um-modifications.js`
array( \'jquery\' ), // Dependant Array
\'1.0\', // Script Version ( Arbitrary )
true // Enqueue in Footer
);
// Localize Our Script so we can use `ajax_url`
wp_localize_script(
\'measurment\',
\'ajax_url\',
$ajax_url
);
// Finally enqueue our script
wp_enqueue_script( \'measurment\' );
}
add_action( \'wp_enqueue_scripts\', \'save_measurment\' );
处理元值的Javascript函数:
jQuery( \'document\' ).ready( function( $ ) {
// Form submission listener
$( \'#savem\' ).submit( function() {
var measrumentData = {};
// Grab our post meta value
measrumentData.profile_name = $( \'#savem #profile_name\' ).val();
measrumentData.value1 = $(\' #savem #value1\').val();
measrumentData.value2 = $(\' #savem #value2\').val();
var jsonString = JSON.stringify(measrumentData);
// Do very simple value validation
$.ajax( {
url : ajax_url, // Use our localized variable that holds the AJAX URL
type: \'POST\', // Declare our ajax submission method ( GET or POST )
data: {data: jsonString},
} )
.success( function( results ) {
console.log( \'User Meta Updated!\' );
} )
.fail( function( data ) {
console.log( data.responseText );
console.log( \'Request failed: \' + data.statusText );
} );
return false; // Stop our form from submitting
} );
} );
最后是ajax回调函数
function measurment_callback() {
// Ensure we have the data we need to continue
if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {
// If we don\'t - return custom error message and exit
header( \'HTTP/1.1 400 Empty POST Values\' );
echo \'Could Not Verify POST Values.\';
exit;
}
$user_id = get_current_user_id(); // Get our current user ID
$data = json_decode(stripslashes($_POST[\'data\']));
foreach($data as $key=>$value)
{
add_user_meta( $user_id, $key, $value );
}
exit;
}
现在发生的事情是,在提交表单时,控制台显示更新的元数据,但phpmyadmin给出错误消息“null不是对象(正在计算‘field\\u id.match(/[^-]+$/)’)”。我不知道怎么了,所以任何帮助都是值得的