javascript - 在 Wordpress 中 Hook AJAX

标签 javascript php ajax wordpress

我一直在钻研 Javascript 和 AJAX 的世界。我非常接近,但出于某种原因,我认为我没有正确地连接到 wordpress ajax 函数。我已经仔细阅读了文档和这个,认为那里已经完成了 99%。

这个应用程序的作用是有一个项目列表。每个都有一个 + 按钮。单击该按钮会弹出一个确认框,如果确认,则获取所需的数据以传递给 php.ini 文件。 php 使用 wpdb->insert 将项目添加到 mysql 中。如果您购买,它也会做一些改变。

js 一直工作到调用,获取正确的值等。如果我硬编码它应该从 POST 获取的值,则单独测试 php 也能正常工作。所以我知道这两个部分都在运行,我只是无法让 js 正确调用 ajax api。有人可以看看这个并让我知道如何将它们连接在一起以便 ajax 调用实际运行 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 件)。我不确定我是否将这些功能 Hook 到 wordpress 上。或者 jQuery 按钮的嵌套函数可能存在问题。我怀疑它是 2 号,因为它似乎工作......我只是从服务器返回 0 而没有任何数据库事件。以下是日志内容。


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

非常感谢您提供的所有帮助和建议!

最佳答案

首先你需要以正确的方式添加钩子(Hook)

// 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
}

一个钩子(Hook)在用户登录时起作用,另一个在用户未登录时起作用(对于任何用户)。如果您正在为登录用户发出 ajax 请求,那么,wp_ajax_nopriv_钩子(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_ajax_script.js文件,你可以这样编码

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

请记住,当从管理面板使用 ajax 时,您不需要使用 wp_localize_script ,因为 2.8 ajaxurl 始终在管理 header 中定义并指向 admin-ajax.php .

关于javascript - 在 Wordpress 中 Hook AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19721859/

相关文章:

php - 做空 isset POST?

javascript - 使用 $_FILES 而不是字段名称的 codeigniter upload->do_upload()

PHP:最简单的方法是在第一个 6 个月前获取月份的日期?

javascript - 我可以从另一个调用一个 js 文件吗?

javascript - jQuery:排序)表不适用于新版本的 jQuery

javascript - 如何更改滚动部分?

php - Ajax 响应出错

javascript - 如何设置可以缩放和拖动的背景图片?

javascript - 跨站点 XmlHttp (XDomainRequest)

.net - Ajax 调用 onbeforeunload 不适用于 Firefox - 适用于 IE