Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

prince69's avatar

How to get product & price when clicked on category using ajax in laravel?

I want to get category-wise products when clicked on a specific category usnig ajax. In this method I get product names & images and successfully load them into view with ajax.

public function getProductByCategory($id) {
    $category = FoodItemCategory::find($id);
    $products = $category->foods;

    return response()->json($products);
}

By this foreach loop, I get product price but I couldn't pass them into view as ajax response

 foreach ($products as $product) {
        foreach ($product->price as $price) {
            $original_price = $price->original_price ;

        }
    }

here is my ajax success response

       success: function(response) {
                $('.products').empty();

                var href = "{{ route('home') }}/";

                $.each(response, function(key, value) {
                    var url = "{{ route('shop.view', ':id') }}";
                    url = url.replace(':id', value.id);

                    $('.products').append("<div class='col-md-6 col-lg-4'>" +
                        "<div class='item'><div class='thumb'>" +
                        "<a href='" + url +
                        "' class='woocommerce-LoopProduct-link woocommerce-loop-product__link'>" +
                        "<img src='" + href + "images/" + value.image +
                        "' height='280px' width='320px'></a><a href='#' data-id='" + value.id +
                        "' class='button product_type_simple add_to_cart_button ajax_add_to_cart'>Add to cart</a>" +
                        "</div><div class='info'><h5 class='woocommerce-loop-product__title'><a href='" +
                        url + "'>" +
                        value.name + "</a></h5>" +
                        "<span class='price'><span class='woocommerce-Price-amount amount'><span class='woocommerce-Price-currencySymbol'> </span>65" +
                        "</span></span></div></div></div>");
                });
            }

Now, How can I load prices into this success function?

0 likes
2 replies
gokulkhatiwada's avatar

create view for products listing and return HTML in ajax response

public function getProductByCategory($id) {
    $category = FoodItemCategory::find($id);
    $products = $category->foods;

    return view('viewname',compact('products'))->render();
}

in javascript

 $('.products').append(response);
prince69's avatar

It did not work. I got a view in response only but it did not append.

Please or to participate in this conversation.