Debug School

rakesh kumar
rakesh kumar

Posted on

How to display data using common function after filtering in laravel using jquery

this is my html data where resultContainerisid through which we display content and paginationContaineris for pagination through which we paginate using jquery

<div class="row" id="resultContainer" style="margin-top:2%;">
    <div class="col-lg-12 col-md-12 col-sm-12 col-12">
        <div class="col-md-12 col-lg-12">
            <div class="card" style="padding: 27px;">

                <div id="resultContent">
                    <!-- Your data results will be added here -->
                </div>
                <div class="card-body" id="paginationContainer">
                    <!-- Pagination buttons will be added here -->
                </div>
            </div>
        </div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

The displayFilteredData function is called if the request is successful when website is loading

This part initializes variables for the current page and items per page. It then calls the loadData function to initiate the data loading process.

// Initial load
loadData();
Enter fullscreen mode Exit fullscreen mode
var currentPage = 1;
var itemsPerPage = 10;
Enter fullscreen mode Exit fullscreen mode

The loadData function retrieves the value of admin_id and determines the URL based on its presence. It then makes an AJAX request to the appropriate URL, and on success, it calls the displayFilteredData function to handle the retrieved data.


function loadData() {
    var id = $('#admin_id').val();
    var isLoggedIn = $('#admin_id').val() !== '';
    var url = (id) ? '/all-influencer-data' : '/influencer-datas';
    console.log(url);

    if (url.includes('all-influencer-data')) {
        $.ajax({
            url: '/all-influencer-data',
            type: 'GET',
            success: function (data) {
                console.log(data);
                displayFilteredData(data);
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    } else {
        $.ajax({
            url: '/influencer-datas',
            type: 'GET',
            success: function (data) {
                console.log(data);
                displayFilteredData(data);
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

The displayFilteredData function takes the retrieved data, checks if it contains filters, and then paginates the data based on the current page and items per page. It also updates the pagination controls and dynamically adds elements to the result container.

function displayFilteredData(data) {
    var resultContainer = $('#resultContent');
    resultContainer.empty();

    if (data && data.filters) {
        console.log("dfg");
        var filters = data.filters;
        console.log(filters);

        var startIndex = (currentPage - 1) * itemsPerPage;
        var endIndex = startIndex + itemsPerPage;
        var paginatedData = filters.slice(startIndex, endIndex);

        var totalPages = Math.ceil(filters.length / itemsPerPage);
        addPaginationControls(totalPages);

        if (paginatedData.length > 0) {
            $.each(paginatedData, function (index, item) {
                resultContainer.append('<p>' + item + '</p>');
            });
        } else {
            resultContainer.append('<p>No data found.</p>');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The addPaginationControls function dynamically creates buttons for each page and attaches a click event to them. When a button is clicked, it updates the current page and triggers a data reload by calling the loadData function.

function addPaginationControls(totalPages) {
    var paginationContainer = $('#paginationContainer');
    paginationContainer.empty();

    for (var i = 1; i <= totalPages; i++) {
        var button = $('<button>', {
            text: i,
            class: 'btn btn-sm btn-primary mr-2',
            click: function () {
                currentPage = parseInt($(this).text());
                loadData();
            }
        });

        paginationContainer.append(button);
    }
}
Enter fullscreen mode Exit fullscreen mode

The displayFilteredData function is called if the request is successful when i filter multiselect

Image description

 function fetch_social_data(filter_by_socialsite, page, search_query) {
            console.log('fetch_social_data function is called');
            $('#user_pic_file').html('');
            var cleanPage = page.toString().replace('amp;', '');
            $.ajax({
                url: "/welcome_influencersocialsite",
                method: "GET",
                data: {
                    filter_by_socialsite: filter_by_socialsite

                },
                success: function(data) {
                    console.log(data + ' - Data in success function');
                    displayFilteredData(data);         },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX request failed: ' + textStatus, errorThrown);
                }
            });
        }
Enter fullscreen mode Exit fullscreen mode

The displayFilteredData function is called if the request is successful when i filter country,state and city

Image description

   function fetch_jobs_data(filter_by_country, filter_by_state, filter_by_city,
        filter_by_search, page) {

       var selectedCountryText = $('#filter_by_country :selected').text();
          console.log(selectedCountryText);
          if (selectedCountryText === 'Select Country') {
        $('#filter_by_state').find('option[value="all"]').text('Select State');
                }  
    var selectedCountryText = $('#filter_by_state :selected').text();
          console.log(selectedCountryText);
          if (selectedCountryText === 'Select State') {
        $('#filter_by_city').find('option[value="all"]').text('Select City');
    } 
        $('#user_pic_file').html('');
        var cleanPage = page ? page.toString().replace('amp;', '') :
            ''; // Check if page is defined before calling toString()
        $.ajax({
            url: "{{ url('/welcome_influencermanualfilter') }}?filter_by_country=" +
                filter_by_country +
                "&filter_by_state=" + filter_by_state + "&filter_by_city=" + filter_by_city +
                "&filter_by_search=" + filter_by_search,
            data: {
                filter_by_country: filter_by_country,
                filter_by_state: filter_by_state,
                filter_by_city: filter_by_city,
                filter_by_search: filter_by_search,
                page: cleanPage // Add the page parameter
            },
            success: function(data) {
                console.log(data + 'data in success welcome_influencermanualfilter function');
                displayFilteredData(data);

                $('#user_pic_file').html('');
                $('#user_pic_file').html(data);
            }
        });
    }
Enter fullscreen mode Exit fullscreen mode

The displayFilteredData function is called if the request is successful, when i click addcart

Image description

function mySocialsClick(button, selectedData) {
    var itemId = button.data('id'); // Get the data-id attribute value
    console.log("Button clicked with data-id:", itemId);
    console.log("Selected sites:", selectedData);

    // Prepare data for the AJAX request
    var formData = new FormData();
    formData.append('itemId', itemId); // Add itemId to formData
    formData.append('selectedData', JSON.stringify(selectedData)); 

    $.ajax({
        url: "{{ route('addcarts.store') }}",
        method: "POST",
        data: formData,
        contentType: false,
        cache: false,
        processData: false,
        dataType: "json",
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // Add CSRF token if needed
          },
        beforeSend: function () {
            // Add any code to execute before sending the AJAX request
        },
        success: function (data) {
           console.log("addcarts.store aata hain");
           var prices = data.prices;
           var social = data.filters;
        var influencer = data.influencer;
        var publisher = data.publisher; 
        console.log('add prices success click ho rha ha', prices);
        var socialSiteCount;
        if (prices && Array.isArray(prices.prices)) {
    // Calculate the number of social sites
    var socialSiteCount = prices.prices.length;   

    console.log('social sites aayega:', social);

    console.log('Number of social sites:', socialSiteCount);
        } else {
            console.log('Prices is not an object with a "prices" array or is undefined.');
        }

        let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
                Publisher ${publisher} has successfully added an influencer ${influencer} for follwing sites with pricerate given below . Please check in the cart.
            </h5>`;
            for (let i = 0; i < socialSiteCount; i++) {
    const entry = prices.prices[i];
    const socialSite = entry.social_site;
    const price = entry.price;

    const socialSiteText = socialSite === 'face' ? `${socialSite}book` : socialSite;
    htmlCode += `<p class="text-center" style="margin: 2px 0; color: blue;">
        Social Site: ${socialSiteText}, Price: $${price} per post.
    </p>`;
}

            console.log('Influencer:', influencer);
            console.log('Publisher:', publisher);
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
            $('#approvessmycart').html(`
            ${htmlCode}
               `);
           displayFilteredData(data);

        },
        error: function (xhr, textStatus, errorThrown) {
            // Handle the error response
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)