Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Joe Bruno
Joe Bruno
35,909 Points

wp_ajax, WordPress, and calling a Class Method

Hello,

Although my code is working, I am trying to refractor it and move my cart_item_add function into my class CartItem. Unfortunately, I cannot get the ajax to fire the method inside of the class. I am pretty sure that the problem surrounds my add_action (wp_ajax....) function and probably the jQuery action function, but I have had no luck trying to fix it, and haven't found any viable insights in the Codex or StackOverflow. Help!

Currently, I have:

In the main plugin.php file:

         add_action( 'wp_ajax_cart_item_add', 'cart_item_add' );
         add_action( 'wp_ajax_nopriv_cart_item_add', 'cart_item_add' );

In class-cart.php at the bottom outside of the class CartItem, I have:

  function cart_item_add() {

        if( isset($_POST['post_id'] ) && is_numeric($_POST['post_id'] ) ) {


            $submitted_id  = esc_html($_POST['post_id']);
            $cart_item     = new CartItem($submitted_id);

            $customer = new Customer(); 
            $user_id  = $customer->id;
            $location = $customer->CART;


             if ($cart_item) {

                $cart_data = $customer->cart_data;
                $post_id   = $cart_item->post_id;

                if ( $cart_item->quantity ) {

                    $quantity = $cart_item->quantity;

                } else {

                    $quantity = 1; 

                }

                $cart_data[$post_id] = array(

                    'id'        => $post_id,
                    'status'    => 'active',
                    'quantity'  => $quantity, 

                    );

                update_user_meta( $user_id, $location, $cart_data );

            } else {

                error_log("Add Item Failed.");
            }

        } else {

            error_log("Add Item Failed to Pass isset");
        }
    }

And my jQuery:

    (function ($) {

         $(document).on('click', ".add-to-cart", function(e){
             e.preventDefault();

            var cartData = $(this).attr('value'); 
            console.log("Clicked");
            console.log(cartData);

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxurl,
            data: { action: 'cart_item_add', post_id: cartData },
            complete: function(data) {
                console.log(data);
                console.log("first success");

                $.ajax({
                 type: "POST",
                 url: ajaxurl,
                 data: { action: "get_cart"},
                 success: function(data) {
                               $('.cart-main').remove();
                                $(".cart-wrapper").append(data).fadeIn('slow');
                           }
            });


            }

           });


    });
  }(jQuery));

As it is - it works. How do I move my function into my class CartItem?

Again, I think the problem is in my add_action calls, and in my jQuery I would have thought I needed something like "CartItem::cart_item_add", but I couldn't get that working either.

Thanks

1 Answer

Andrew Shook
Andrew Shook
31,709 Points

Joe, right now you are creating your cart class with the add_item function, so you can't move it into the class without replacing the add_item with another function that instantiates the class. You could use a static creations method, but I think that would be a little over kill. I would look at breaking you cart code into two classes, a model class and a controller class. I would then have the ajax call instantiate the controller class and have it decide what to do next (i.e. add item, remove item, checkout). I would also let controller class create a cart class and a customer class(both models).