前端的Ajax和WordPress – 数据库不更新

所以我正在使用WordPress网站。 我在获取用户输入以更新数据库时遇到了一些困难。

JS:

var ID = $(this).attr('id'); var name = $("#name_input_"+ID).val(); var createDate = $("#created_input_"+ID).val(); var stats = $("#status_input_"+ID).val(); var dateExpire = $("#disbanded_input_"+ID).val(); var dataString = 'id=' + ID + '&name=' + name + '&createDate=' + createDate + '&stats=' + stats + '&dateExpire=' + dateExpire; // can place loading image here if (name.length > 0 || createDate.length > 0 || stats.length > 0 || dateExpire.length > 0) { $.ajax({ type: "POST", url: "../edit-items.php", data: dataString, cache: false, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); }, success: function (html) { $("#name_"+ID).html(name); $("#createDate_"+ID).html(createDate); $("#stats_"+ID).html(stats); $("#dateExpire_"+ID).html(dateExpire); } }); } else { alert("Enter text to make an edit."); } }); 

PHP(edit-items.php)

 global $wpdb; if($_POST['id']) { $id = esc_sql($_POST['id']); $name = esc_sql($_POST['name']); $created = esc_sql($_POST['createDate']); $stats = esc_sql($_POST['stats']); $dateExpire = esc_sql($_POST['dateExpire']); $query = "UPDATE items SET itemName='$name', createDate='$created', itemStats='$stats', dateExpire='$dateExpire' WHERE committee_id='$id';" $wpdb->query($wpdb->prepare($query)); } 

每当我尝试更新表时,我都可以在前端成功完成,但在刷新时,数据更改不会成功。 检查数据库进一步validation数据是否未被更改……似乎“成功”传递了AJAX,但由于某种原因,它不会更新数据库。

对此有任何见解会有所帮助!

编辑决定开始使用admin-ajax.php方法。 一切都是一样的,除了我把JS中的url: "/wp-admin/admin-ajax.php",更改为url: "/wp-admin/admin-ajax.php", edit-items.php url: "/wp-admin/admin-ajax.php",edit-items.php的代码现在在functions.php如下所示:

  function editCommittee() { global $wpdb; if($_POST['id']) { $id = esc_sql($_POST['id']); $name = esc_sql($_POST['name']); $created = esc_sql($_POST['createDate']); $stats = esc_sql($_POST['stats']); $dateExpire = esc_sql($_POST['dateExpire']); $wpdb->update('itemsTable', array( 'name' => $name ), array( 'committee_id' => $id ), array( '%s' ) ); echo $id; exit(); } } add_action('wp_ajax_editItems', 'editItems'); 

好的,首先本地化你的ajaxurl对象

 add_action( 'wp_enqueue_scripts', 'frontend_enqueued_scripts' ); /** * Localization object * * @since 1.0.0 */ function frontend_enqueued_scripts() { wp_enqueue_script( 'script', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true ); wp_localize_script( 'script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), )); } 

如果您在functions.php有一个将前端脚本wp_enqueue_script wp_localize_script位置, wp_enqueue_scriptwp_localize_script部分放在那里。 此外,如果您将ajax调用javascript放在一个名为custom.js的文件中, custom.js更改名称以指向它。 我总是使用custom.js作为文件存储我所有与主题相关的javascript。

上面的代码将在您的前端创建一个ajax_object对象,该对象可用于custom.js的代码,因为您已将其附加到该脚本。 排队文件和本地化脚本(在我们的案例script )中的句柄必须相同才能使其工作。

然后你可以在functions.php文件中创建,或者在你放置ajax函数的任何包含文件中创建一个回调函数

 /** * Front and back end ajax hooks. */ add_action( 'wp_ajax_edit_committee', 'edit_committee' ); add_action( 'wp_ajax_nopriv_edit_committee', 'edit_committee' ); /** * Ajax callback function * * @since 1.0.0 */ function edit_committee() { global $wpdb; if ( isset( $_POST['id'], $_POST['committee_nonce'] ) && wp_verify_nonce( sanitize_key( $_POST['committee_nonce'] ), 'committee_nonce_action' ) && '' !== $_POST['id'] ) { // Input var okay. $id = ( isset( $_POST['id'] ) && '' !== $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ); : ''; // Input var okay. $name = ( isset( $_POST['name'] ) && '' !== $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ); : ''; // Input var okay. $created = ( isset( $_POST['create_date'] ) && '' !== $_POST['create_date'] ) ? sanitize_text_field( wp_unslash( $_POST['create_date'] ) ); : ''; // Input var okay. $stats = ( isset( $_POST['stats'] ) && '' !== $_POST['stats'] ) ? sanitize_text_field( wp_unslash( $_POST['stats'] ) ); : ''; // Input var okay. $date_expire = ( isset( $_POST['date_expire'] ) && '' !== $_POST['date_expire'] ) ? sanitize_text_field( wp_unslash( $_POST['date_expire'] ) ); : ''; // Input var okay. $updated = $wpdb->update( 'itemsTable', array( 'name' => $name ), array( 'committee_id' => $id ), array( '%s' ) ); if( false !== $updated ) { wp_die( 'success' ); } else { wp_die( 'fail' ); } } } 

我添加了消毒检查。 在表单中包含一个用于提交数据的随机数是至关重要的。

您可以通过放置添加它

 wp_nonce_field( 'committee_nonce_action', 'committee_nonce' ); 

在前端的

元素内。 这将生成一个nonce ,这是一个很好的安全措施,尤其是在您写入数据库时​​。

回调函数将检查nonce是否已设置,如果$_POST['id']变量设置为非空,并将首先validationnonce。

然后你可以继续执行该function。

即使您没有使用它们,我也会将所有$POST变量留在那里,但也许您以后会想要使用它们。 我也对它们进行了消毒并将它们删除了。

// Input var okay. 评论是出于phpcs的目的,你可以忽略它。

然后你预先形成更新。 如果数据库中有itemsTable ,则应使用您提供的数据更新它。

最后但并非最不重要的是javascript代码。 我假设您正在通过某种按钮点击执行ajax调用。 这需要改变它才能工作(我使用#update_button ,你会放置你的按钮的正确id或类)

 jQuery(document).ready(function($) { 'use strict'; $('#update_button').on('click', function(e){ e.preventDefault(); var ID = $(this).attr('id'); // Button that is clicked is in $(this) object var name = $('#name_input_'+ID).val(); var create_date = $('#created_input_'+ID).val(); var stats = $('#status_input_'+ID).val(); var date_expire = $('#disbanded_input_'+ID).val(); // Can place loading image here if ( name.length > 0 || create_date.length > 0 || stats.length > 0 || date_expire.length > 0 ) { $.ajax({ type: 'POST', url: ajax_object.ajaxurl, data: { 'action' : 'edit_committee', 'id' : ID, 'name' : name, 'create_date' : create_date, 'stats' : stats, 'date_expire' : date_expire, 'committee_nonce' : $( '#committee_nonce' ).val() }, cache: false, error: function( jqXHR, textStatus, errorThrown ) { console.log( jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown ); }, success: function (html) { if ( html == 'success' ) { $('#name_'+ID).html(name); $('#createDate_'+ID).html(create_date); $('#stats_'+ID).html(stats); $('#dateExpire_'+ID).html(date_expire); } } }); } else { alert('Enter text to make an edit.'); } }); }); 

我还将变量名称更改为short_name格式,而不是shortName 。 我觉得整洁。

请注意,对于url,我们使用了ajax_object.ajaxurl – 这是ajax_object开始的本地化ajax_object ,引用admin-ajax.php文件的正确路径。 数据只是您的字符串,但写为对象。

因此,当您单击该按钮时,您的ajax调用会将所有数据放入全局$_POST变量中。

您可以通过运行检查器并单击网络> XHR选项卡来检查它

在此处输入图像描述

此外,如果你不确定你的$_POST变量是什么,请放

 error_log(print_r($_POST, true)); 

在您的edit_committee()函数中,在validation检查之前(if条件)。 如果在wp-config.php启用了调试

 define('WP_DEBUG', true); ini_set('log_errors',TRUE); ini_set('error_reporting', E_ALL); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); 

你将在WordPress安装的根目录中有error_log.txt ,你可以检查$_POST变量的内容是什么。

希望这可以帮助 ;)

在此处输入图像描述

这是问题,对于我们使用的ajax请求http://example.com/wp-admin/admin-ajax.php
您的数据字符串也应该是cantain &action=editItems (与您在wp_ajax_editItems使用的wp_ajax_editItems

你ajax请求代码应该看起来像……

  $.ajax({ type: "POST", url: "/wp-admin/admin-ajax.php", data: dataString + '&action=editItems', cache: false, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); }, success: function (html) { $("#name_"+ID).html(name); $("#createDate_"+ID).html(createDate); $("#stats_"+ID).html(stats); $("#dateExpire_"+ID).html(dateExpire); } }); 

有关更多详细信息,请访问https://codex.wordpress.org/AJAX_in_Plugins

希望有所帮助:)

我很确定你没有将POST数据发送到PHP文件 – 检查它。 在php中键入var_dump($_POST) ,并在ajax的成功部分添加console.log(html)

尝试将JS中的dataString变量更改为:

 var dataString = { id:ID, name:name, createDate:createDate, stats:stats, dateExpire:dateExpire }; 
 $wpdb->update( 'table', array( 'column' => $name), array( 'ID' => 1 ), array( '%s'), array( '%d' ) );