2016-06-08 16 views
4

在我woocommerce網站,我已經改變了購物車頁面,刪除按鈕「更新購物車」,創建2個按鈕來添加和刪除產品的項目,如我表現出這樣的畫面:更新車

enter image description here

當我點擊量按鈕我要調用同一個函數,如果我按下按鈕更新購物車。

對於這個我使用AJAX,但它不會做任何事情。

首先在我function.php文件我有這樣的:

function update_my_cart() { 
    // here update then cart 
    var_dump("execute"); 
    } 
    add_action('wp_ajax_update_my_cart', 'update_my_cart'); // If called from admin panel 
    add_action('wp_ajax_nopriv_update_my_cart', 'update_my_cart'); 



    add_action('wp_enqueue_scripts', 'rct_enqueue_scripts'); 

    if (! function_exists('rct_enqueue_scripts')) : 

    function rct_enqueue_scripts() { 
    wp_enqueue_script('rct-js', get_template_directory_uri() . '/js/themeCoffee.js', array(), '1.0', true); 
    wp_localize_script('rct-js', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'))); 
    } 

    endif; 

在我的jQuery文件,我有這樣的:

updatecart = function(qty) { 
    var currentVal, data, item_hash, request; 
    currentVal = void 0; 
    data = void 0; 
    item_hash = void 0; 
    currentVal = parseFloat(qty); 
    request = $.ajax({ 
     url: 'ajax_object.ajax_url', 
     method: 'POST', 
     data: { 
     quantity: currentVal, 
     action: 'update_my_cart' 
     }, 
     dataType: 'html' 
    }); 
    request.done(function(msg) { 
     alert('cart update '); 
    }); 
    request.fail(function(jqXHR, textStatus) { 
     alert('Request failed: ' + textStatus); 
    }); 
    }; 

我得到這個錯誤:

Failed to load resource: the server responded with a status of 404 (Not Found) 

因爲我嘗試加載my_website/cart/ajax_object.ajax_url

在此先感謝!

+0

感謝@LoicTheAztec我已經修改了文件,像你這樣的建議。並用新更改更改問題,但我仍然收到相同的錯誤。任何想法! – Stone

+0

@LoicTheAztec我有一個錯誤,我在我的ajax函數url中有這個:'ajax_object.ajax_url',正確的是沒有引號。現在的作品,謝謝你的幫助 – Stone

+0

汽車** t **沒有車 – Midas

回答

6

你必須忘記這個重要的過程:

add_action('wp_enqueue_scripts', 'add_my_ajax_scripts'); 
add_my_ajax_scripts(){ 
    // Here you register your script located in a subfolder `js` of your active theme 
    wp_enqueue_script('ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true); 
    // Here you are going to make the bridge between php and js 
    wp_localize_script('ajax-script', 'cart_ajax', array('ajaxurl' => admin_url('admin-ajax.php'))); 
} 

然後你會在url:檢索'ajaxurl''cart_ajax'在你的JavaScript文件:

$.ajax({ 
    url: 'cart_ajax.ajaxurl', 
    ... 
}) 

您的JavaScript功能將無法正常工作。 下面是一些例子功能,你需要做什麼