skip to Main Content

I’m very new at AJAX JavaScript, and i got tast for filtering data in Laravel 10 without refresh using AJAX
but no luck yet.

This is the code for my blade view :

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
    
        const clickableElements = document.querySelectorAll('.clickable');
        // Fungsi untuk mengambil dan menampilkan data campaign berdasarkan kategori
        function filterCampaignByCategory(category) {
            $.ajax({
                type: 'GET',
                url: '/filter', // Sesuaikan dengan rute Anda
                data: { filter: category },
                success: function(data) {
                    var campaigns = data.campaigns;
                    var campaignList = $('#daftar_campaign');
                    campaignList.empty();

                    // Loop melalui data campaign dan tambahkan ke daftar
                    $.each(campaigns, function(key, campaign) {
                        campaignList.append(
                            '<div class="popular-causes__sinlge">' +
                            '<div class="popular-causes__img">' +
                            '<img height="300px" src="http://127.0.0.1:8001/storage/' + campaign.BannerCampaign + '" alt="">' +
                            '<div class="popular-causes__category">' +
                            '<p>' + campaign.KategoriCampaign + '</p>' +
                            '</div>' +
                            '</div>' +
                            '<div class="popular-causes__content" style="width: 370px">' +
                            '<div class="popular-causes__title" style="height: 100px">' +
                            '<h3><a href="campaign-details.html">' + campaign.NamaCampaign + '</a></h3>' +
                            '</div>' +
                            '<div class="popular-causes__progress" style="height: 200px">' +
                            '<div class="bar">' +
                            '<div class="bar-inner count-bar" data-percent="' + campaign.percentageCompleted + '%">' +
                            '<div class="count-text">' + campaign.percentageCompleted + '%</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="popular-causes__goals">' +
                            '<p><span>' + campaign.HasilDonasiCampaign + '</span> Terkumpul</p>' +
                            '<p><span>' + campaign.TargetCampaign + '</span> Target</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>');
                    });
                }
            });
        }

        clickableElements.forEach(function(element) {
            element.addEventListener('click', function() {
                const value = element.getAttribute('data-value');
                filterCampaignByCategory(value);
            });
        });

        function sendGetRequest(value) {
            window.location.href = "/?filter=" + value;
        }

        // Tambahkan event listener untuk ikon kategori
        $('.category-icon').on('click', function() {
            var selectedCategory = $(this).data('category');
            filterCampaignByCategory(selectedCategory);
        });

        
        // Memuat semua campaign saat halaman pertama kali dimuat
         // Menggunakan '' untuk memuat semua campaign
    
    </script>

    <!--campaign Start-->
    <section class="popular-causes">
        <div class="container pb-5 mb-5">
            <div class="block-title text-left">
                <h4>Help the People</h4>
                <h3>Our Popular Campaigns</h3>
            </div>
            <div class="row">
                <div class="col-xl-12">
                    <div class="popular-causes__carousel owl-theme owl-carousel" id="daftar_campaign">
                        @foreach ($campaigns as $campaign)
                            <div class="popular-causes__sinlge">
                                <div class="popular-causes__img">
                                    <img height="300px" src="http://127.0.0.1:8001/storage/{{ $campaign->BannerCampaign }}"
                                        alt="">
                                    <div class="popular-causes__category">
                                        <p>{{ $campaign->KategoriCampaign }}</p>
                                    </div>
                                </div>
                                <div class="popular-causes__content" style="width: 370px">
                                    <div class="popular-causes__title" style="height: 100px">
                                        <h3><a href="campaign-details.html">{{ $campaign->NamaCampaign }}</a>
                                        </h3>
                                        
                                    </div>
                                    <div class="popular-causes__progress" style="height: 200px">
                                        <div class="bar">
                                            <div class="bar-inner count-bar"
                                                data-percent="{{ $campaign->percentageCompleted }}%">
                                                <div class="count-text">{{ $campaign->percentageCompleted }}%</div>
                                            </div>
                                        </div>
                                        <div class="popular-causes__goals">
                                            <p><span>{{ $campaign->HasilDonasiCampaign }}</span> Terkumpul</p>
                                            <p><span>{{ $campaign->TargetCampaign }}</span> Target</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </section>

and this is the code for my controller :

public function filter(Request $request){
        $filter = $request->input('filter');

        if (empty($filter)) {
            $campaigns = Campaign::with('user')
                        ->select('NamaCampaign','UrlCampaign','KategoriCampaign','BannerCampaign','MulaiCampaign','AkhirCampaign','TargetCampaign','HasilDonasiCampaign')
                        ->where('Prioritas', 1)
                        ->where('Aktif', 1)
                        ->latest('idCampaign')
                        ->get();
        } else {
            $campaigns = Campaign::with('user')
                        ->select('NamaCampaign','UrlCampaign','KategoriCampaign','BannerCampaign','MulaiCampaign','AkhirCampaign','TargetCampaign','HasilDonasiCampaign')
                        ->where('KategoriCampaign', $filter)
                        ->where('Prioritas', 1)
                        ->where('Aktif', 1)
                        ->latest('idCampaign')
                        ->get();
        }
        
        return response()->json(['campaigns' => $campaigns]);
    }

enter image description here
this i the default page before filtering

enter image description here
and this is after the filtering data, the filter work but upon investigation the Ajax is ignoring my
div class making it weird look :

<div class="popular-causes__carousel owl-theme owl-carousel" id="daftar_campaign">

I already tried many solutions and haven’t found luck yet, I really love to see what or thoughts why this is happening.

2

Answers


  1. Following the comments, move the HTML into a unique .blade.php file. Let’s call it campaigns.blade.php, inside of resources/views:

    <div class="popular-causes__carousel owl-theme owl-carousel" id="daftar_campaign">
      @foreach($campaigns as $campaign)
        <div class="popular-causes__sinlge">
          <div class="popular-causes__img">
            <img height="300px" src="http://127.0.0.1:8001/storage/{{ $campaign->BannerCampaign }}" alt="" />
            <div class="popular-causes__category">
              <p>{{ $campaign->KategoriCampaign }}</p>
            </div>
          </div>
          <div class="popular-causes__content" style="width: 370px">
            <div class="popular-causes__title" style="height: 100px">
              <h3>
                <a href="campaign-details.html">{{ $campaign->NamaCampaign }}</a>
              </h3>    
            </div>
            <div class="popular-causes__progress" style="height: 200px">
              <div class="bar">
                <div class="bar-inner count-bar" data-percent="{{ $campaign->percentageCompleted }}%">
                  <div class="count-text">{{ $campaign->percentageCompleted }}%</div>
                </div>
              </div>
              <div class="popular-causes__goals">
                <p>
                  <span>{{ $campaign->HasilDonasiCampaign }}</span> Terkumpul
                </p>
                <p>
                  <span>{{ $campaign->TargetCampaign }}</span> Target
                </p>
              </div>
            </div>
          </div>
        </div>
      @endforeach
    </div>
    

    In your existing .blade.php file, "include" this one:

    <section class="popular-causes">
      <div class="container pb-5 mb-5">
        <div class="block-title text-left">
          <h4>Help the People</h4>
          <h3>Our Popular Campaigns</h3>
        </div>
        <div class="row">
          <div id="campaignsContainer" class="col-xl-12">
            @include('campaigns', ['campaigns' => $campaigns])
          </div>
        </div>
      </div>
    </section>
    

    Notice how I added id="campaignsContainer" to the <div> immediately surrounding the @include() section. This is important for later.

    Now, in your Controller, modify your return statement:

    public function filter(Request $request){
      $campaigns = Campaign::with('user') /* ... */ ->get();
    
      return response()->json(['html' => view('campaigns', ['campaigns' => $campaigns])->render()], 200);
    }
    

    Finally, modify your JS:

    function filterCampaignByCategory(category) {
      $.ajax({
        type: 'GET',
        url: '/filter',
        data: { filter: category },
        success: function(response) {
          $('#campaignsContainer').html(response.html);
        }
      });
    }
    

    The line $('#campaignsContainer').html(response.html); will take the returned HTML from the Controller, which is an exact duplicate of your existing HTML (since @include('view', ...) and view('view', ...) generate the same HTML) and overwrite it with the new $campaigns that are generated inside of the Controller.

    And that should do it!

    Login or Signup to reply.
  2. base on your script try to comment or delete this line : campaignList.empty();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search