Woocommerce Products: Ajax Pagination reloading page issue - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Sunday, July 23, 2023

Woocommerce Products: Ajax Pagination reloading page issue

Wordpress Version 6.2.2 Woocommerce Version 7.8.2 Permalinks set to /%postname%/ Product Permalinks set to /produkt/ Theme: TwentyTwentyOne

How can I prevent the whole page to refresh each time i use the pagination? Everything works fine, except the fact that each time i click a pagination link, the whole page refreshes. The url is updated like

h t t p s : / / w e b s i t e . c o m / ? p a g e d = 1

h t t p s: / / w e b s i t e . c o m / ? p a g e d = 2

h t t p s: / / w e b s i t e . c o m / ? p a g e d = 3

which is also fine.

Here is the code:

functions.php:

// Enqueue scripts and localize variables for AJAX pagination
function enqueue_ajax_pagination_scripts() {
wp_enqueue_script('ajax-pagination-script', get_template_directory_uri() . 'assets/js/custom-ajax.js', array('jquery'), '1.0', true);

// Localize variables to be used in the AJAX script
wp_localize_script('ajax-pagination-script', 'twentytwentyone_ajax_object', array(
    'ajax_url' => admin_url('admin-ajax.php'),));} 
add_action('wp_enqueue_scripts', 'enqueue_ajax_pagination_scripts'); 

// Callback function for AJAX pagination
function load_products_ajax_callback() {
$page = max(1, (int)$_POST['page']); // Ensure the current page is at least 1

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 22,
    'paged' => $page,
    'orderby' => 'title', // Sort by product name
    'order' => 'ASC',    // Order in ascending (A to Z) 
);

$products = new WP_Query($args);

ob_start(); // Start output buffering

if ($products->have_posts()) {
    echo '<div class="table-2255"><div class="table-thead-2255"><div class="table-tr-2255"></div></div><div class="table-tbody-2255">';

    while ($products->have_posts()) {
        $products->the_post();
        global $product;

        // Get the product data
        $product_name = $product->get_name();
        $product_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
        $product_permalink = get_permalink();

        // Output the product details

        echo '<div class="table-tr-2255">';
        echo '<div class="table-td-2255 entryImage"><img src="' . $product_image[0] . '" alt="' . $product_name . '"></div>';
        echo '<div class="table-td-2255 entryName"><h2 class="c1"><a class="c1" href="' . $product_permalink . '">' . $product_name . '</a></h2></div>';

        // Additional product attributes

        $attributes = $product->get_attributes();
        if ($attributes && !empty($attributes)) { // Add a check for $attributes
            $counter = 1;
            foreach ($attributes as $attribute) {
                $attribute_label = wc_attribute_label($attribute->get_name());
                $attribute_value = array();

                // Get attribute options as labels
                $options = $attribute->get_terms();
                foreach ($options as $option) {
                    $attribute_value[] = $option->name;
                }

                $css_class = 'entry' . $counter;

                echo '<div class="table-td-2255 ' . $css_class . '"><span class="attribute-label c1">' . $attribute_label . ':</span> <span class="attribute-value">' . implode(', ', $attribute_value) . '</span></div>';

                $counter++;
            }
        }

        echo '</div>';
    }
    echo '</div></div>';

    if ($products->max_num_pages > 1) {
        // Output the AJAX pagination links

        $pagination_args = array(
            'base' => admin_url('admin-ajax.php') . '?action=load_products_ajax&paged=%#%',
            'format' => '?paged=%#%',
            'current' => $page,
            'total' => $products->max_num_pages,
            'prev_text' => '<< Zurück',
            'next_text' => 'Weiter >>',
            'mid_size' => 5, // Number of links to display on each side of the current page
        );

        echo '<div class="pagination2255 paginationtop">';
        echo paginate_links($pagination_args);
        echo '</div>';
    }
} else {
    echo 'No products found.';
}

wp_reset_postdata();

$output = ob_get_clean(); // Get the buffered output
echo $output;

wp_die(); // End the AJAX request
 }
 add_action('wp_ajax_load_products_ajax', 'load_products_ajax_callback');
 add_action('wp_ajax_nopriv_load_products_ajax', 'load_products_ajax_callback'); // Allow non-logged-in users to use the AJAX endpoint

custom-ajax.js:

jQuery(document).ready(function($) {
   // Define a variable to keep track of the current page
   var currentPage = 1;

  // Function to handle the AJAX request and update the product list
 function loadProducts(page) {
    // Fetch the product list from the server using JavaScript Fetch API
fetch(twentytwentyone_ajax_object.ajax_url + '?action=load_products_ajax&paged=' + page)
  .then(function(response) {
    return response.text();
  })
  .then(function(response) {
    // Update the product list with the new content
    $('#product-list-container').html(response);
    // Update the current page
    currentPage = page;
  })
  .catch(function(error) {
    // Handle error if necessary
  });
   }

    // Initial loading of products (page 1)
 loadProducts(1);

 // Handle click on pagination links
 $(document).on('click', '.pagination-link', function(e) {
e.preventDefault(); // Prevent the default link behavior
var page = parseInt($(this).attr('data-page'));
// Load products for the clicked page
loadProducts(page);
 });
});

template-home.php:

<div id="content2255inner">

<!-- Product Display -->
<div id="product-list-container">
    <?php
    $paged = max(1, (int) get_query_var('page')); // Ensure the current page is at least 1

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 22,
        'paged' => $paged,
        'orderby' => 'title', // Sort by product name
        'order' => 'ASC',    // Order in ascending (A to Z)
    );

    $products = new WP_Query($args);

    if ($products->have_posts()) {
        echo '<div class="table-2255"><div class="table-thead-2255"><div class="table-tr-2255"></div></div><div class="table-tbody-2255">';

        while ($products->have_posts()) {
            $products->the_post();
            global $product;

            // Get the product data
            $product_name = $product->get_name();
            $product_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
            $product_permalink = get_permalink();

            echo '<div class="table-tr-2255">';
            echo '<div class="table-td-2255 entryImage"><img src="' . $product_image[0] . '" alt="' . $product_name . '"></div>';
            echo '<div class="table-td-2255 entryName"><h2 class="c1"><a class="c1" href="' . $product_permalink . '">' . $product_name . '</a></h2></div>';

            $attributes = $product->get_attributes();
            if ($attributes && !empty($attributes)) { // Add a check for $attributes
                $counter = 1;
                foreach ($attributes as $attribute) {
                    $attribute_label = wc_attribute_label($attribute->get_name());
                    $attribute_value = array();

                    // Get attribute options as labels
                    $options = $attribute->get_terms();
                    foreach ($options as $option) {
                        $attribute_value[] = $option->name;
                    }

                    $css_class = 'entry' . $counter;

                    echo '<div class="table-td-2255 ' . $css_class . '"><span class="attribute-label c1">' . $attribute_label . ':</span> <span class="attribute-value">' . implode(', ', $attribute_value) . '</span></div>';

                    $counter++;
                }
            }

            echo '</div>';
        }
        echo '</div></div>';

        if ($products->max_num_pages > 1) {
            // Output the AJAX pagination links
            $pagination_args = array(
                'base' => add_query_arg('paged', '%#%'), // Use the current page URL with the addition of the 'paged' query parameter
                'format' => '?paged=%#%',
                'current' => $paged,
                'total' => $products->max_num_pages,
                'prev_text' => '<< Zurück',
                'next_text' => 'Weiter >>',
                'mid_size' => 5, // Number of links to display on each side of the current page
            );

            echo '<div class="pagination2255 paginationtop">';
            echo paginate_links($pagination_args);
            echo '</div>';
        }
    } else {
        echo 'No products found.';
    }

    wp_reset_postdata();
    ?>
</div>


source https://stackoverflow.com/questions/76741231/woocommerce-products-ajax-pagination-reloading-page-issue

No comments:

Post a Comment