0

How can i render component that is sent from controller via an ajax request? For example i want to dynamically filter product using this method:

  1. Load the index URL
  2. Fetch the products based on the filter category or return all the products using ajax

My ajax Code:

$(document).ready(function () {
    filterData();

    // Filter data function
    function filterData() {
        // Initializing loader
        $('#product-listing-row').html('<div id="loading" style="" ></div>');
        var action = 'fetchData';
        var subCategory = getFilter('sub-category');

        /* LARAVEL META CSRF REQUIREMENT */
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // Ajax Call
        $.ajax({
            url: "/shop/filter",
            method: "POST",
            data: {action: action, subCategory: subCategory},
            success: function (data) {
                $('#product-listing-row').html(data);
            }
        });
    }

    // Get Filter by class name function
    function getFilter(className) {
        var filter = [];
        $('.' + className + ':checked').each(function () {
            filter.push($(this).val());
        });

        //console.log(filter);

        return filter;
    }

    $('.common-selector').click(function () {
        filterData();
    });
});

I am getting all the filters from ProductController

Instead of manually writing html in controller I want to return the specific component from the controller

ProductController:

public function productFilter() {
            if (!request()->action) abort('500');
            
            // Starting the query for products which are active
            $products = Product::where('is_active', '1');
            
            //dump(request()->subCategory);
            
            /* Checking the filters */
            // sub category exists
            if (request()->subCategory) $products = $products->where('sub_category_id', request()->subCategory);
            
            // Completing the query
            $products = $products->orderBy('created_at', 'DESC')->paginate(15);
            // Adding reviews and total review
            $products = Product::setProductReviewTotalReviewsAttr($products);
            
            foreach ($products as $product)
                //view('components.shop-product', ['product' => $product])->render();
                echo '<x-shop-product :product="$product"></x-shop-product>';
        }

Instead of getting the components rendered, I am receiving the whole string echoed out. Is there any way i can just get the components rendered?

Thanks in advance

3 Answers 3

1

Actually now I found a way to do it myself

I applied the following to the ProductController

return View::make("components.shop-product")
    ->with("product", $product)
    ->render();

Updated Code:

        public function productFilter() {
            if (!request()->action) abort('500');
            
            // Starting the query for products which are active
            $products = Product::where('is_active', '1');
            
            //dump(request()->subCategory);
            
            /* Checking the filters */
            // sub category exists
            if (request()->subCategory) $products = $products->where('sub_category_id', request()->subCategory);
            
            // Completing the query
            $products = $products->orderBy('created_at', 'DESC')->paginate(15);
            // Adding reviews and total review
            $products = Product::setProductReviewTotalReviewsAttr($products);
            
            $output = '';
            
            foreach ($products as $product) {
                $output .= View::make("components.shop-product")
                    ->with("product", $product)
                    ->render();
            }

            if (count($products) > 0)
                echo $output;
            else
                echo '<div class="col">No Data</div>';
        }
Sign up to request clarification or add additional context in comments.

Comments

0

with laravel > 8 you can use \Blade::render directly in your controller to render even anonymouse components, here I'm rendering a table component with a lot of properties:

class componentController extends Controller {

public function index(){

   $table = [
       :tableid => "table"
       :thead => ["id","name","job"]
       :data => [
           ["1","marcoh","captain"],
           ["2","sanji","cook"]
       ],
       tfoot => false
   ];
    
    // Renders component table.blade.php
    return \Blade::render('
        <x-table
            :tableid="$tableid"
            :thead="$thead"
            :data="$data"
            tfoot
        />
    ', $table);

...

Comments

0

you can use this way.

    $('.add-new-input').on('click', function () {
    $.ajax({
        url: '{{ route('getMultiLanguageComponent') }}',
        type: 'GET',
        data: {
            prefix: $(this).data('prefix'),
            name: $(this).data('name'),
        },
        beforeSend: function () {
            // before send
        },
        success: function (response) {
            // success
        },
        error: function (error) {
            // error
        }
    });
});

in controller

    public function getMultiLanguageComponent(Request $request)
{
    $component = new MultiLanguageForCurriculum(null, $request->input('prefix'));
    return $component->render()->with(['name' => $request->input('name'), 'prefixName' => $request->input('prefix'), 'required' => true]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.