在 Wordpress 中挂钩 AJAX [英] Hook AJAX in Wordpress

查看:34
本文介绍了在 Wordpress 中挂钩 AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在钻研 Javascript 和 AJAX 的世界.我非常接近,但出于某种原因,我认为我没有正确地使用 wordpress ajax 功能.我已经翻阅了文档和这个,并认为那里有 99%.

I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have poured through the docs and this and think it is 99% there.

这个应用程序的作用是有一个项目列表.每一个都有一个+按钮.点击按钮会弹出一个确认框,如果确认就抓取需要的数据传递给php.php 使用 wpdb->insert 将该项添加到 mysql 中.如果您购买,它也会有一些变化.

Is what this app does is there is a list of items. Each one with a + button. Clicking the button pops up a confirm box, and if confirmed grabs the needed data to pass to the php. The php adds the item into mysql with wpdb->insert. It also does some changes if you buy.

js 一直工作到调用,获取正确的值等.如果我对它应该从 POST 获取的值进行硬编码,单独测试 php 也能正常工作.所以我知道这两部分都在运行,我只是无法让 js 正确调用 ajax api.有人可以看看这个,让我知道如何将它们连接在一起,以便 ajax 调用实际运行 php?

The js works all the way up to the call, grabbing the right values etc. Testing the php separately works as well if I hard code the values it is supposed to grab from POST. So I KNOW both pieces run, I just can't get the js to call the ajax api right. Can someone please take a look at this and let me know how to hook these together so the ajax call actually runs the 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();
}

?>

我很确定它是 2 个事物中的 1 个(或 2 个).我不确定我是否正确地将这些功能挂钩到 wordpress.或者我的 jQuery 按钮的嵌套函数可能存在问题.我怀疑它是 2 号,因为它似乎有效......我只是从服务器返回 0,没有任何数据库活动.日志内容如下.

I am pretty sure it is 1 (or 2) of 2 things. I am not sure if I am hooking these functions to wordpress right. Or there might be issues with nested functions I have for the jQuery button. I doubt it is number 2 though because it seems to work... I just get a 0 back from the server without any database activity. Here is what the log says.

cID = 112 ?charID=112:538
charMoney = 9990 ?charID=112:539
thisValue = + ?charID=112:540
iID = 664 ?charID=112:541
buy = 0 ?charID=112:542
ajaxurl = http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php ?charID=112:543
data = [object Object] ?charID=112:550
Object {action: "addItemAJAX", charID: 112, itemID: 664, buyItem: 0} ?charID=112:551
XHR finished loading: "http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php". jquery-1.9.1.js:8526
send jquery-1.9.1.js:8526
jQuery.extend.ajax jquery-1.9.1.js:7978
jQuery.(anonymous function) jquery-1.9.1.js:7614
(anonymous function) ?charID=112:554
jQuery.event.dispatch jquery-1.9.1.js:3074
elemData.handle

非常感谢大家的帮助和建议!

Thank you very much for all of the help and suggestions!

推荐答案

首先你需要以适当的方式添加钩子

First of all you need to add hooks in proper way

// 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_ajax_nopriv_ 钩子.

One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.

将您的 js/ajax 代码保存在 yourthemefolder/js/myAjaxScript.js 中的一个单独文件中,并将以下代码保存在您的 functions.php文件

Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file

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_ajax_script.js 文件中,你可以这样编码

In your my_ajax_script.js file, you may code like this

var data = {
     action: 'addItemAJAX_callback',
     // ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
     // response is an object
     // ...
});

Alos 记住,当从管理面板使用 ajax 时,你不需要使用 wp_localize_script,因为 2.8 ajaxurl 总是在管理头中定义并指向 admin-ajax.php.

Alos remember, when using ajax from admin panel, you don't need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.

这篇关于在 Wordpress 中挂钩 AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆