Javascript Wordpress中的钩子AJAX
我一直在钻研Javascript和AJAX的世界。我非常接近,但出于某种原因,我认为我没有正确地使用wordpress ajax函数。我已经翻遍了所有的文件和这些,我认为99%都在那里 此应用程序所做的就是提供一个项目列表。每个都有一个+按钮。单击按钮会弹出一个确认框,如果确认,则获取所需的数据以传递给php。php使用wpdb->insert将该项添加到mysql中。如果你买的话,它也会做一些改变 js一直工作到调用,获取正确的值等等。如果我硬编码它应该从POST获取的值,那么单独测试php也可以工作。所以我知道这两部分都在运行,我只是无法让js正确调用ajax api。有人能看一下这一点,让我知道如何将这些连接在一起,以便ajax调用实际运行php吗 这是代码Javascript Wordpress中的钩子AJAX,javascript,php,ajax,wordpress,Javascript,Php,Ajax,Wordpress,我一直在钻研Javascript和AJAX的世界。我非常接近,但出于某种原因,我认为我没有正确地使用wordpress ajax函数。我已经翻遍了所有的文件和这些,我认为99%都在那里 此应用程序所做的就是提供一个项目列表。每个都有一个+按钮。单击按钮会弹出一个确认框,如果确认,则获取所需的数据以传递给php。php使用wpdb->insert将该项添加到mysql中。如果你买的话,它也会做一些改变 js一直工作到调用,获取正确的值等等。如果我硬编码它应该从POST获取的值,那么单独测试php也
<?php
add_action( 'admin_footer', 'addItemAJAX_javascript' );
function addItemAJAX_javascript() {
$adminAJAX = admin_url('admin-ajax.php');
?>
<script type="text/javascript" language="JavaScript">
$(function() {
$( "input[name=btnAddItem]" )
.button()
.click(function( event ) {
event.preventDefault();
var confirmAction = confirm('Are you sure you want to add this item to your character?');
if (confirmAction==true) {
// build data for AJAX call
var cID = $('#hdnCharID').val();
cID = cID*1;
var charMoney = $('#hdnCharMoney').val();
var thisValue = $(this).val();
var iID = $(this).prev('input[id="hdnItemID"]').val()
iID = iID*1;
//Add or Buy Item
if (thisValue != "+") {
var buy = 1;
}
else {
var buy = 0;
}
var ajaxurl = <?php echo json_encode($adminAJAX); ?>;
console.log('cID = ' + cID);
console.log('charMoney = ' + charMoney);
console.log('thisValue = ' + thisValue);
console.log('iID = ' + iID);
console.log('buy = ' + buy);
console.log('ajaxurl = ' + ajaxurl);
var data = {
action: 'addItemAJAX',
charID: cID,
itemID: iID,
buyItem: buy
};
console.log('data = ' + data);
console.log(data);
//WP ajax call
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
else {
console.log('add item aborted');
}
});
});
</script>
<?php
};
addItemAJAX_javascript();
// PHP SIDE OF AJAX - Handeling Request //// AJAX PROCESSING /////////////////////////////////
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
function addItemAJAX_callback() {
global $wpdb;
$charID = intval($_POST['charID']);
$itemID = intval($_POST['itemID']);
$buyItem = intval($_POST['buyItem']);
// //get item details
$getItemDetailsSQL = "
Select
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_name,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_description,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_cost,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_weight
From
fyxt_wp_db_fatcow.fyxt_items
Where
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items = $itemID";
$getItemDetailsResults = $wpdb->get_row($getItemDetailsSQL);
$iID = $getItemDetailsResults->idfyxt_items;
$iName = $getItemDetailsResults->fyxt_item_name;
$iDesc = $getItemDetailsResults->fyxt_item_description;
$iCost = $getItemDetailsResults->fyxt_item_cost;
$iWeight = $getItemDetailsResults->fyxt_item_weight;
$charItemTable = fyxt_char_items;
$wpdb->insert(
$charItemTable,
array (
idfyxt_item => $iID,
idfyxt_character => $charID,
item_name => $iName,
item_desc => $iDesc,
item_cost => $iCost,
item_weight => $iWeight,
item_quant => 1,
equip => 0,
carried => 1
)
);
$wpdb->print_error();
$newItemAdded = $wpdb->insert_id;
//remove cash if item is bought
if ($buyItem == 1 ) {
$curCharMoneySQL =
"Select
fyxt_wp_db_fatcow.fyxt_characters.char_money
From
fyxt_wp_db_fatcow.fyxt_characters
Where
fyxt_wp_db_fatcow.fyxt_characters.idfyxt_character = $charID";
$curCharCash = $wpdb->get_var($curCharMoneySQL);
$wpdb->print_error();
$newCash = $curCharCash - $iCost;
$changeCashSQL = "
UPDATE fyxt_characters
SET
char_money = $newCash
WHERE
idfyxt_character = $charID";
$changeCash = $wpdb->query($changeCashSQL);
$wpdb->print_error();
}
$debugArray = Array();
array_push($debugArray,$charID, $itemID, $buyItem, $getItemDetailsSQL, $getItemDetailsResults,$newItemAdded, $newCash);
echo $debugArray ;
die();
}
?>
非常感谢所有的帮助和建议 我不会详细介绍您的代码,因为它似乎有点难以复制(有关此问题,请参阅)。但我将概述如何使用Ajax和WordPress(从: 1) 将JavaScript文件排队并本地化。 我们可以直接在页眉或页脚上打印,而不是排队,但这不是一种好的做法。本地化将以干净的方式将PHP值传递给JS。
我假设您正在处理一个主题,否则将
get\u stylesheet\u directory\u uri()
更改为plugins\u url()
3) Ajax回调和响应
Ajax回调进行安全检查,并使用wp\u send\u json.*
处理响应:
function addItemAJAX_callback()
{
check_ajax_referer( 'my_ajax_validation', 'security' );
$my_thing = something();
if( !$my_thing )
wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
else
wp_send_json_success( $my_thing );
}
4) 最后是剧本
这是必不可少的。您可以通过本地化对象
我的\u处理程序
传递所需的任何信息。我们从回答中检查了三件事:
- 完全失败:无法访问回调或未通过安全性
- 部分失败:已到达回调,但返回了
json\u错误
- 成功:继续你的事情
首先,您需要以适当的方式添加挂钩
// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );
// For the users that are logged in:
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
// ajax handler
function addItemAJAX_callback()
{
// code goes here
// since $debugArray is an array, so
die(json_encode($debugArray)); // last line
}
一个钩子在用户登录时工作,另一个钩子在用户未登录时工作(对于任何用户)。如果您正在为登录用户发出ajax请求,则需要使用wp\u ajax\u nopriv\uwp
hook
将您的js/ajax
代码保存在yourthemefolder/js/myAjaxScript.js
的单独文件中,并将以下代码保存在functions.php
文件中
add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
// for pluggin, you may use "plugin_dir_url( __FILE__ )"
wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
// Following code will let you use "ajaxObj.ajax_url" to get the
// ajax url (admin-ajax.php) in your my_ajax_scriptjs file
wp_localize_script(
'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
在您的my\u ajax\u script.js文件中,您可以这样编码
var data = {
action: 'addItemAJAX_callback',
// ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
// response is an object
// ...
});
请记住,当从管理面板使用ajax时,您不需要使用wp\u localize\u script
,因为2.8 ajaxurl总是在管理标题中定义,并指向admin ajax.php
OK这样做了,但它对我不起作用,或者它是,我搞砸了。我的代码在这里:它在firebug中进行了查询,数据似乎是正确的,但响应始终为0。这是我第一次构建插件时遇到的问题。@Sam,您没有正确访问。另外,搜索add_submenu_page
+admin_print_scripts-$hook
哦,我想我找到了你说的内容。谢谢你给我指出了正确的方向。非常感谢你的回答。我添加了wp_ajax/wp_ajax_nopriv。如果这只对登录用户显示,我需要nopriv吗?我还添加了下面建议的更详细的错误报告。我得到了“AJAX错误:无响应”,所以第一个。这是否意味着脚本被钩住了?如果是,是否可以对其不响应的原因进行故障排除?这一切都好吗,只是没有通过安全检查?我要试着让临时电话在这里工作。我只是想弄明白这一切是如何协同工作的。再次感谢!有没有人知道是什么原因导致这一切不起作用?有服务器设置要检查吗?有没有其他方法可以实现同样的目标?我需要让它工作起来,但我无法克服这个没有响应的AJAX问题。很好的解释!我不是高级Wordpress开发者。你的帖子仍然有用。尤其是当您在手机上登录并尝试新功能时。它总是失败!谢谢
jQuery( document ).ready( function( $ ) {
var data = {
action: 'addItemAJAX_callback',
security: my_handler.ajaxnonce
};
$( '#my-submit' ).click( function(e) {
e.preventDefault();
$.post(
my_handler.ajaxurl,
data,
function( response ) {
// ERROR HANDLING
if( !response.success ) {
// No data came back, maybe a security error
if( !response.data )
$( '#my-answer' ).html( 'AJAX ERROR: no response' );
else
$( '#my-answer' ).html( response.data.error );
}
else
$( '#my-answer' ).html( response.data );
}
);
});
});
// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );
// For the users that are logged in:
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
// ajax handler
function addItemAJAX_callback()
{
// code goes here
// since $debugArray is an array, so
die(json_encode($debugArray)); // last line
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
// for pluggin, you may use "plugin_dir_url( __FILE__ )"
wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
// Following code will let you use "ajaxObj.ajax_url" to get the
// ajax url (admin-ajax.php) in your my_ajax_scriptjs file
wp_localize_script(
'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
var data = {
action: 'addItemAJAX_callback',
// ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
// response is an object
// ...
});