• Hello,
    I am struggeling with this for two days and I can’t get the point where I’m wrong. I coded a little class to add a cart-button and a small widget to display the content of the cart in the sidebar. I am using a session ($_SESSION[‘wcmshop’][‘cart’]). It contains an array with all clicked products. For the button I use a form button. When you click the button the function add_to_cart inside the class is fired which checks, if this product is allready inside the session’s cart array. Without Ajax everything works fine. As soon as I try to add Ajax to prevent page reload and add some effects everything stopps working. I followed this very good example on https://www.garyc40.com/2012/03/5-tips-for-using-ajax-in-wordpress/.
    Here is the code for the buttons:

    <form method="post" action="" id="add-31">
    <input type="hidden" name="item-nonce" value="whatever" />
    <input type="hidden" id="qty-31" name="qty" size="3" value="1" />
    <button type="submit" id="addItem-31" name="addItem-31" class="addButton" value="add">Add</button>
    </form>

    Inside the constructor of my class I wrote this

    add_action('wp_ajax_add_to_cart', array(&$this,'add_to_cart'));
    add_action('wp_ajax_nopriv_add_to_cart', array(&$this, 'add_to_cart'));

    Inside the javascript I used this code:

    jQuery('.addButton').live("click", function(event) {
    event.preventDefault();
    var ItemID = jquery(this).attr('id').replace('addItem-','');
    var qty = jQuery('#qty-' + ItemID + '').val();
    jQuery.ajax({
    url: MyAjax.url,
    type: "POST",
    data: "action=add_to_cart&itemID=" + ItemID +"&qty=" + qty,
    success: function() {
    //Only for testing
    alert(ItemID + ' ' + qty);
    }
    });
    return false;
    });

    The function add_to_cart inside the class looks like this:

    function add_to_cart() {
    $ItemID = $_REQUEST['ItemID'];
    $qty = $_REQUEST['qty'];
    etc...
    }

    As mentioned before: you click the button, the alert pops up showing the correct values and that’s it. No update of the session. Even when I hit F5…

    I don’t know where I’m wrong… Any help would be appreciated!!!

    Dietmar

  • The topic ‘WordPress and Ajax’ is closed to new replies.