阿贾克斯& amp;前端上的WordPress-数据库未更新 [英] Ajax & WordPress on Front End - Database not updating
问题描述
因此,我正在WordPress网站上工作.我在获取用户输入以更新数据库方面有些困难.
So I'm working on a WordPress website. I'm having a bit of a difficult time getting the user input to update the database.
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)
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));
}
每当我尝试更新表时,我都能在前端成功完成它,但是在刷新时,数据更改不会停留.检查数据库是否进一步验证了数据没有更改……似乎成功"正在传递到AJAX中,但是由于某种原因,它没有更新数据库.
Whenever I try to update the table, I am able to do it successfully on the front end, but on refresh, the data change does not stick. Checking the database further verifies that the data has not been changed... It seems like the "success" is passing in the AJAX, but for some reason, it's not updating the database.
对此有任何见识会有所帮助!
Any insight on this would be helpful!
修改
决定开始使用admin-ajax.php
方法.一切都一样,除了我将JS中的url更改为url: "/wp-admin/admin-ajax.php",
并且edit-items.php
中的代码现在在functions.php
中像这样:
Edit
Decided to start using the admin-ajax.php
method. Everything is the same except I changed the url in the JS to url: "/wp-admin/admin-ajax.php",
and the code from edit-items.php
is now in functions.php
like so:
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
对象
Ok, so first localize your ajaxurl
object
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
部分.另外,如果要将调用Ajax的javascript放置在未调用custom.js
的文件中,请更改名称以指向该文件.我总是将custom.js
用作存储与主题相关的所有javascript的文件.
If you have, in your functions.php
a place where you are enqueuing front end scripts place the wp_enqueue_script
and wp_localize_script
part in there. Also if you are placing your ajax calling javascript inside a file that is not called custom.js
change the name to point to it. I always use custom.js
as a file where I store all my theme related javascript.
上面的代码将在前端创建一个ajax_object
对象,该对象可用于custom.js
中的代码,因为您已将其附加到该脚本.排队的文件和本地化脚本(在我们的情况下为script
)中的句柄必须相同,才能正常工作.
The above code will create an ajax_object
object on your front end that will be available to the code inside the custom.js
, since you've attached it to that script. The handles in the enqueued file and localized script (in our case script
) must be the same for this to work.
然后,您可以在functions.php
文件或放置ajax函数的任何包含文件,回调函数
Then you can create, in functions.php
file, or in any included file where you put your ajax functions, a callback function
/**
* 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' );
}
}
}
我添加了消毒检查.至关重要的是,您要在表单中包含一个用于提交数据的随机数.
I added the sanitization checks. It's crucial that you include a nonce in your form that you'll use to submit the data.
您可以通过放置
wp_nonce_field( 'committee_nonce_action', 'committee_nonce' );
前端<form>
元素内的
.这将生成一个 nonce ,这是一种很好的安全措施,尤其是在您写入数据库时
inside the <form>
element on your front end. This will generate a nonce, which is a good security measure, especially when you're writing to the database.
回调函数将检查是否设置了随机数,是否设置了$_POST['id']
变量并且不为空,并且将首先验证随机数.
The callback function will check if the nonce is set, if the $_POST['id']
variable is set and not empty, and will first verify the nonce.
然后,您可以继续执行该功能.
Then you can carry on with the execution of the function.
即使您没有使用它们,我也将所有$POST
变量留在了那里,但是也许以后您想使用它们.我还对它们进行了消毒并毫不费力.
I left all the $POST
variables there even though you're not using them, but maybe you'll want to use them later on. I also sanitized them and unslashed them.
// Input var okay.
注释用于phpcs,您可以忽略它.
The // Input var okay.
comment is for phpcs purposes, you can ignore that.
然后执行更新.如果数据库中有itemsTable
,则应使用您提供的数据对其进行更新.
Then you preform the update. If you have the itemsTable
in the database it should update it with the data you provided.
最后但并非最不重要的是javascript代码.我假设您正在通过某种按钮单击来执行ajax调用.需要对其进行更改以使其起作用(我使用了#update_button
,您将放置正确的ID或按钮的类)
The last but not the least is the javascript code. I assumed that you are preforming the ajax call on some kind of button click. This needs to be changed for it to work (I used #update_button
, you'll place the correct id or class of your button)
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
.我觉得更整洁了.
I've also changed variable names to short_name
format, instead of shortName
. I find that neater.
请注意,对于url,我们使用的是ajax_object.ajaxurl
-这是从头开始本地化的ajax_object
,指的是admin-ajax.php
文件的正确路径.数据只是您的字符串,而是作为对象写入的.
Notice that for the url, we used ajax_object.ajaxurl
- this is the localized ajax_object
from the beginning, referencing to the correct path of the admin-ajax.php
file. The data is just your string, but written as an object.
因此,当您单击按钮时,ajax调用会将所有数据放入全局$_POST
变量中.
So when you click the button, your ajax call will put all your data in a global $_POST
variable.
您可以通过运行检查器并单击网络> XHR选项卡来进行检查
You can check it by having inspector running and clicking Network > XHR tab
如果您不确定$_POST
变量的含义,请输入
Also if you're not sure what your $_POST
variable holds, put
error_log(print_r($_POST, true));
在edit_committee()
函数中的
,就在验证检查之前(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
变量的内容是什么.
You'll have error_log.txt
in the root of your WordPress installation, and you can check what the contents of the $_POST
variable is.
希望这会有所帮助;)
这篇关于阿贾克斯& amp;前端上的WordPress-数据库未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!