我尝试通过ajax更新数据,但没有成功。我做错了什么?以下是jquery ajax代码
函数中的php代码。php
function update_records(){
global $wpdb;
echo $id = $_POST[\'update_record\'];
$db_updated = $wpdb->update( $wpdb->prefix.\'contact_form\',
array(\'names\' => $_POST[\'update_name\'],
\'emails\' => $_POST[\'update_email\'],
\'gender\' => $_POST[\'update_gender\'],
\'age\' => $_POST[\'update_age\']), array( \'ID\' => $id ) );
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );
jquery ajax代码
jQuery(\'.upd_btn\').click(function(){
var id = jQuery(this).attr(\'data-id\');
var name = jQuery(this).attr(\'data-name\');
var email = jQuery(this).attr(\'data-email\');
var gender = jQuery(this).attr(\'data-gender\');
var age = jQuery(this).attr(\'data-age\');
alert(age);
$.ajax({
url: \'<?php echo admin_url(\'admin-ajax.php\');?>\',
type: \'POST\',
data:{
action: \'display_func\',
update_record:id,
// update_name:name,
// update_email:email,
// update_gender:gender,
// update_age:age,
},
success: function( data ){
// alert("Records are successfully update");
location.reload();
}
});
});
ajax错误屏幕截图-
https://prnt.sc/wdon1x
最合适的回答,由SO网友:Had1z 整理而成
首先,在jquery事件处理程序中action
参数的值应为后面的字符串wp_ajax_
和wp_ajax_nopriv_
. 因此,在您的示例中action
应该是update_records
. 所以display_func
是错误的
然后在php代码的第3行中echo
应删除关键字
因此您的php代码应该如下所示:
function update_records(){
global $wpdb;
$id = $_POST[\'update_record\'];
$db_updated = $wpdb->update( $wpdb->prefix.\'contact_form\',
array(
\'names\' => $_POST[\'update_name\'],
\'emails\' => $_POST[\'update_email\'],
\'gender\' => $_POST[\'update_gender\'],
\'age\' => $_POST[\'update_age\']
),
array( \'ID\' => $id )
);
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );
SO网友:Baikare Sandeep
请在将数据插入或更新到数据库之前清理数据,以防止攻击者攻击Read Documenation:
function update_records(){
global $wpdb;
$id = intval(sanitize_text_field($_POST[\'update_record\']));
$db_updated = $wpdb->update( $wpdb->prefix.\'contact_form\',
array(
\'names\' => sanitize_text_field($_POST[\'update_name\']),
\'emails\' => sanitize_email($_POST[\'update_email\']),
\'gender\' => sanitize_text_field($_POST[\'update_gender\']),
\'age\' => intval(sanitize_text_field($_POST[\'update_age\']))
),
array( \'ID\' => $id )
);
}
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_update_records", "update_records" );