0

I am still very weak in Ajax, but they told me that this is a way out of the situation that I have developed.

I have a javascript function that filters categories. There is also alternation of lists in php.blade.

When I click on "All", all blogs are displayed and the alternation is working properly. When I select the "desired category", all blogs from this category are displayed, but alternation does not work.

I was prompted that you can is to call one ajax functional on category selection and return the HTML response on that ajax call. But I don't know how to do this, can anyone help?

JavaScript

$('.category-filter_item').click(function(){
    $('.category-filter_item').removeClass('active')
    $(this).addClass('active')
    var dataFilter = $(this).attr('data-filter');
    $('.blog-list').hide()
    $(dataFilter).show()
})

php.blade

@extends('layouts.app')

@section('content')
<div class="container">
<div class="category-filter" id="filter">
    <div class="category-filter_item active" data-filter="*">All</div>
    @foreach($categories as $category)
    <div class="category-filter_item" data-filter=".category_{{$category->id}}">{{ $category->title }}</div>
    @endforeach
</div>

@foreach ($blogs as $index => $blog)
    <div class="blog-list">
        @if ($index % 2 === 1)  //Alternation
            <div class="blog blog--left" >
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @else

            <div class="blog blog--right">
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @endif
    </div>
@endforeach
</div>
@endsection

Controller

public function index()
    {
        $blogs = Blog::all();
        $categories = Category:all();

        return view('blog', compact('blogs', 'categories'));
    }
  • Please check this link: https://stackoverflow.com/questions/69281730/filtering-data-by-category/69282481#69282481 – KudosIntech Sep 22 '21 at 13:36

1 Answers1

0

Need to create new route and controller function to return only the selected category blogs and that should be in json format

Once that is done need to use the ajax call to the above route in the click function defined. Capture the response and then iterate and generate the html that should be inside the blog-list in your script. then update the html inside blog-list value.

refer this link

refer this for making ajax call link

Tharunkumar
  • 170
  • 3
  • 17