Partage
  • Partager sur Facebook
  • Partager sur Twitter

Pagination Ajax json php aide pour le HTML

Demande d'aide pour transmettre des données ajax avec du html

Anonyme
    22 juin 2018 à 8:26:58

    Bonjour,

    Donc, j'ai pris le framework pagination de 'SimplePagination JS'

    mais j'ai un soucis, étant données que j'ai fait en sorte que le filter et pagination de base sois transmis en ajax/JSON.

    j'ai réussie le premier pour faire en sorte que cela sois mis dans une balise {"donnees", "HTML ici" }

    sauf que quand je fait la pagination vers l'autre page cela charge pas comme je voudrais, sa charge les donnees de Json sans l'html et cela me bloque.

    le filtre fonctionne très bien json -> screen -> https://img1.lght.pics/2fmk.png

    mais la pagination je n'arrive vraiment pas quand je passe la page 2 ou je revien sur la 1 sa donne sa:

    screen : https://img.lght.pics/2fmS.png

    voici ce que j'ai fait: le problème vien de la ligne 378

    (function($) {
    // class JS pagination
        var methods = {
            init: function(options) {
                var o = $.extend({
                    items: 1,
                    itemsOnPage: 1,
                    pages: 0,
                    displayedPages: 5,
                    edges: 2,
                    currentPage: 0,
                    hrefTextPrefix: '#page-',
                    hrefTextSuffix: '',
                    prevText: 'Précédent',
                    nextText: 'Suivant',
                    ellipseText: '…',
                    cssStyle: '',
                    listStyle: '',
                    labelMap: [],
                    selectOnClick: true,
                    nextAtFront: false,
                    invertPageOrder: false,
                    useStartEdge: true,
                    useEndEdge: true,
                    onPageClick: function(pageNumber, event) {
                        // Callback triggered when a page is clicked
                        // Page number is given as an optional parameter
                    },
                    onInit: function() {
                        // Callback triggered immediately after initialization
                    }
                }, options || {});
    
                var self = this;
    
                o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
                if (o.currentPage)
                    o.currentPage = o.currentPage - 1;
                else
                    o.currentPage = !o.invertPageOrder ? 0 : o.pages - 1;
                o.halfDisplayed = o.displayedPages / 2;
    
                this.each(function() {
                    self.addClass(o.cssStyle + ' simple-pagination').data('pagination', o);
                    methods._draw.call(self);
                });
    
                o.onInit();
    
                return this;
            },
    
            selectPage: function(page) {
                methods._selectPage.call(this, page - 1);
                return this;
            },
    
            prevPage: function() {
                var o = this.data('pagination');
                if (!o.invertPageOrder) {
                    if (o.currentPage > 0) {
                        methods._selectPage.call(this, o.currentPage - 1);
                    }
                } else {
                    if (o.currentPage < o.pages - 1) {
                        methods._selectPage.call(this, o.currentPage + 1);
                    }
                }
                return this;
            },
    
            nextPage: function() {
                var o = this.data('pagination');
                if (!o.invertPageOrder) {
                    if (o.currentPage < o.pages - 1) {
                        methods._selectPage.call(this, o.currentPage + 1);
                    }
                } else {
                    if (o.currentPage > 0) {
                        methods._selectPage.call(this, o.currentPage - 1);
                    }
                }
                return this;
            },
    
            getPagesCount: function() {
                return this.data('pagination').pages;
            },
    
            setPagesCount: function(count) {
                this.data('pagination').pages = count;
            },
    
            getCurrentPage: function() {
                return this.data('pagination').currentPage + 1;
            },
    
            destroy: function() {
                this.empty();
                return this;
            },
    
            drawPage: function(page) {
                var o = this.data('pagination');
                o.currentPage = page - 1;
                this.data('pagination', o);
                methods._draw.call(this);
                return this;
            },
    
            redraw: function() {
                methods._draw.call(this);
                return this;
            },
    
            disable: function() {
                var o = this.data('pagination');
                o.disabled = true;
                this.data('pagination', o);
                methods._draw.call(this);
                return this;
            },
    
            enable: function() {
                var o = this.data('pagination');
                o.disabled = false;
                this.data('pagination', o);
                methods._draw.call(this);
                return this;
            },
    
            updateItems: function(newItems) {
                var o = this.data('pagination');
                o.items = newItems;
                o.pages = methods._getPages(o);
                this.data('pagination', o);
                methods._draw.call(this);
            },
    
            updateItemsOnPage: function(itemsOnPage) {
                var o = this.data('pagination');
                o.itemsOnPage = itemsOnPage;
                o.pages = methods._getPages(o);
                this.data('pagination', o);
                methods._selectPage.call(this, 0);
                return this;
            },
    
            getItemsOnPage: function() {
                return this.data('pagination').itemsOnPage;
            },
    
            _draw: function() {
                var o = this.data('pagination'),
                    interval = methods._getInterval(o),
                    i,
                    tagName;
    
                methods.destroy.call(this);
    
                tagName = (typeof this.prop === 'function') ? this.prop('tagName') : this.attr('tagName');
    
                var $panel = tagName === 'UL' ? this : $('<ul' + (o.listStyle ? ' class="' + o.listStyle + '"' : '') + '></ul>').appendTo(this);
    
                // Generate Prev link
                if (o.prevText) {
                    methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage - 1 : o.currentPage + 1, {
                        text: o.prevText,
                        classes: 'prev'
                    });
                }
    
                // Generate Next link (if option set for at front)
                if (o.nextText && o.nextAtFront) {
                    methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {
                        text: o.nextText,
                        classes: 'next'
                    });
                }
    
                // Generate start edges
                if (!o.invertPageOrder) {
                    if (interval.start > 0 && o.edges > 0) {
                        if (o.useStartEdge) {
                            var end = Math.min(o.edges, interval.start);
                            for (i = 0; i < end; i++) {
                                methods._appendItem.call(this, i);
                            }
                        }
                        if (o.edges < interval.start && (interval.start - o.edges != 1)) {
                            $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                        } else if (interval.start - o.edges == 1) {
                            methods._appendItem.call(this, o.edges);
                        }
                    }
                } else {
                    if (interval.end < o.pages && o.edges > 0) {
                        if (o.useStartEdge) {
                            var begin = Math.max(o.pages - o.edges, interval.end);
                            for (i = o.pages - 1; i >= begin; i--) {
                                methods._appendItem.call(this, i);
                            }
                        }
    
                        if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
                            $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                        } else if (o.pages - o.edges - interval.end == 1) {
                            methods._appendItem.call(this, interval.end);
                        }
                    }
                }
    
                // Generate interval links
                if (!o.invertPageOrder) {
                    for (i = interval.start; i < interval.end; i++) {
                        methods._appendItem.call(this, i);
                    }
                } else {
                    for (i = interval.end - 1; i >= interval.start; i--) {
                        methods._appendItem.call(this, i);
                    }
                }
    
                // Generate end edges
                if (!o.invertPageOrder) {
                    if (interval.end < o.pages && o.edges > 0) {
                        if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
                            $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                        } else if (o.pages - o.edges - interval.end == 1) {
                            methods._appendItem.call(this, interval.end);
                        }
                        if (o.useEndEdge) {
                            var begin = Math.max(o.pages - o.edges, interval.end);
                            for (i = begin; i < o.pages; i++) {
                                methods._appendItem.call(this, i);
                            }
                        }
                    }
                } else {
                    if (interval.start > 0 && o.edges > 0) {
                        if (o.edges < interval.start && (interval.start - o.edges != 1)) {
                            $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                        } else if (interval.start - o.edges == 1) {
                            methods._appendItem.call(this, o.edges);
                        }
    
                        if (o.useEndEdge) {
                            var end = Math.min(o.edges, interval.start);
                            for (i = end - 1; i >= 0; i--) {
                                methods._appendItem.call(this, i);
                            }
                        }
                    }
                }
    
                // Generate Next link (unless option is set for at front)
                if (o.nextText && !o.nextAtFront) {
                    methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {
                        text: o.nextText,
                        classes: 'next'
                    });
                }
            },
    
            _getPages: function(o) {
                var pages = Math.ceil(o.items / o.itemsOnPage);
                return pages || 1;
            },
    
            _getInterval: function(o) {
                return {
                    start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
                    end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
                };
            },
    
            _appendItem: function(pageIndex, opts) {
                var self = this,
                    options, $link, o = self.data('pagination'),
                    $linkWrapper = $('<li></li>'),
                    $ul = self.find('ul');
    
                pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);
    
                options = {
                    text: pageIndex + 1,
                    classes: ''
                };
    
                if (o.labelMap.length && o.labelMap[pageIndex]) {
                    options.text = o.labelMap[pageIndex];
                }
    
                options = $.extend(options, opts || {});
    
                if (pageIndex == o.currentPage || o.disabled) {
                    if (o.disabled || options.classes === 'prev' || options.classes === 'next') {
                        $linkWrapper.addClass('disabled');
                    } else {
                        $linkWrapper.addClass('page-item active');
                    }
                    $link = $('<a class="page-link current">' + (options.text) + '</a>');
                } else {
                    $link = $('<a href="' + o.hrefTextPrefix + (pageIndex + 1) + o.hrefTextSuffix + '" class="page-link">' + (options.text) + '</a>');
                    $link.click(function(event) {
                        return methods._selectPage.call(self, pageIndex, event);
                    });
                }
    
                if (options.classes) {
                    $link.addClass(options.classes);
                }
    
                $linkWrapper.append($link);
    
                if ($ul.length) {
                    $ul.append($linkWrapper);
                } else {
                    self.append($linkWrapper);
                }
            },
    
            _selectPage: function(pageIndex, event) {
                var o = this.data('pagination');
                o.currentPage = pageIndex;
                if (o.selectOnClick) {
                    methods._draw.call(this);
                }
                return o.onPageClick(pageIndex + 1, event);
            }
    
        };
    
        $.fn.pagination = function(method) {
    
            // Method calling logic
            if (methods[method] && method.charAt(0) != '_') {
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else if (typeof method === 'object' || !method) {
                return methods.init.apply(this, arguments);
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.pagination');
            }
    
        };
    
        "use strict";
    
        $(".filtre1-groupe").select2({
            placeholder: "Aucun Filtre",
            minimumResultsForSearch: -1
        });
    
    })(jQuery);
    
    //filter
    function searchFilter(pageNumber) {
        pageNumber = pageNumber ? pageNumber : 0;
    
        var keywords = $('#keywords').val();
        var sortBy = $('#sortBy').val();
    
        $.post({
            url: LinkAction + 'loadGroupePageAll' + ExtsAction,
            data: '?page=' + pageNumber + '&keywords=' + keywords + '&sortBy=' + sortBy,
            beforeSend: function() {
                $('.loading-overlay').show();
            },
            success: function(html) {
                $('.loading-overlay').fadeOut("slow");
                $('#target-content').html(html.donnees);
            }
        }, 'json');
    	
        return false;
    }
    
    //pagination
    $(function() {
        $(document).ready(function() {
            $('.pagination').pagination({
                items: $('#GroupeTotal').val(),
                itemsOnPage: $('#LimitParPage').val(),
                cssStyle: 'light-theme',
                currentPage: 1,
                onPageClick: function(pageNumber) {
                    jQuery("#target-content").html('chargement...');
                    jQuery("#target-content").load(LinkAction + 'loadGroupePageAll' + ExtsAction + '?page=' + pageNumber);
                }
            });
        });
    });

    php

    <?php
            require($_SERVER['DOCUMENT_ROOT'].'/core/system.php');
    		
    		header('Content-Type: application/json');
    		
    		$donnees = '';
    
    		$whereSQL = $orderSQL = $system->filtertext('');
    		$keywords = $system->filtertext($_POST['keywords']);
    		$sortBy =  $system->filtertext($_POST['sortBy']);
    		
    		$GetKeywords = $system->filtertext($_GET["keywords"]);
    		
    		if(!empty($_GET["keywords"])) 
    		{
    			if (isset($_GET["keywords"])) 
    			{ 
    		        $keywords = $GetKeywords; 
    		    }
    		}
    		
    		if(!empty($keywords)) 
    		{
    			if (isset($keywords)) 
    			{ 
                    $whereSQL = "AND name LIKE '%".$keywords."%'";
    			}
    		}
    		
    	    $SortBy_Check  = [
    		    'default',  
    			'totalmb', 
    			'totallk',
    			'derniers',
    			'msgroupe'
    		];
    		
    		if (!in_array($sortBy, $SortBy_Check)) 
    		{
    			$donnees .='<div class="alert alert-warning col-lg-12 col-md-12"><b>Attention</b> le filtre n\'est pas disponible ou n\'existe plus. Merci de choisir un autre filtre pour continuer votre recherche correctement dans les groupes..</div>';
    			$SortByFilterSecu = $orderSQL = "ORDER BY id DESC";
    			$limit = '6';
    		} 
    		else  
    		{
    			if($sortBy == 'default') 
    			{
    				$limit = '6';
                    $SortByFilterSecu = $orderSQL = "WHERE name LIKE '%".$keywords."%' ORDER BY id DESC";
    			} 
    			else if($sortBy == 'totalmb') 
    			{
    				$query1 = $db->connect()->prepare('SELECT COUNT(*) AS total_membre FROM cms_groupes ORDER BY total_membre DESC');
    				$query1->execute();
    				$count1 = $query1->fetchColumn(0);
    				
    				$limit = $count1[0];
    				
                    $SortByFilterSecu = $orderSQL = "WHERE total_membre > 0 ".$whereSQL." ORDER BY total_membre DESC";
    			} 
    			else if($sortBy == 'totallk') 
    			{
    				$query2 = $db->connect()->prepare('SELECT COUNT(*) AS total_like FROM cms_groupes ORDER BY total_like DESC');
    				$query2->execute();
    				$count2 = $query2->fetchColumn(0);
    				
    				$limit = $count2[0];
    				
                    $SortByFilterSecu = $orderSQL = "WHERE total_like > 0 ".$whereSQL." ORDER BY total_like DESC";
    		    } 
    			else if($sortBy == 'derniers') 
    			{				
    				$mtn = time() - 60 * 60 * 24;
    				$actuel = time();
    			
    				$query3 = $db->connect()->prepare('SELECT COUNT(*) AS date_creation FROM cms_groupes WHERE date_creation > ? AND date_creation < ? ORDER BY date_creation DESC');
    				$query3->execute([$mtn, $actuel]);
    				$count3 = $query3->fetchColumn(0);
    				
    				$limit = $count3[0];
    				
                    $SortByFilterSecu = $orderSQL = "WHERE date_creation > '$mtn' AND date_creation < '$actuel' ".$whereSQL." ORDER BY date_creation DESC";
    			} 
    			else if($sortBy == 'msgroupe') 
    			{
    				$limit = '1';
    				$MyID = $membre->get('id');
                    $SortByFilterSecu = $orderSQL = "WHERE owner_id = '$MyID' ".$whereSQL." ORDER BY owner_id DESC";	
    		    }
    
    			if(!empty($sortBy)) {
                    $SortByFilterSecu;
    			} else {
    				$limit = '6';
    				$orderSQL = "WHERE name LIKE '%".$keywords."%' ORDER BY id DESC";
    			}
    		}
    
    		$GetPage = intval($_GET["page"]);
    		
    		if (isset($_GET["page"])) { 
    		    $page = $GetPage; 
    		} else { 
    			$page = 1;
    		}  
    		
    		$start_from = ($page-1) * $limit;  
    
    	    $query = $db->connect()->prepare('SELECT * FROM cms_groupes '.$orderSQL.' LIMIT '.$start_from.','.$limit);
            $query->execute();
    		
            $fetch = $query->fetchAll();
                for ($g = 0; $g < count($fetch); $g++) {
    			
    			$confidentialite_button = ($fetch[$g]['confidentialite'] != "1") ? '<button type="button" class="btn-groupe-rej btn btn-default btn-xs">Rejoindre le groupe</button>' : null;			
    			$confidentialite_status = ($fetch[$g]['confidentialite'] != "0") ? '<div class="groupe-icon-status-close"><a data-toggle="tooltip" data-placement="bottom" data-original-title="Groupe Fermer" title=""  href="#"> Fermer</a></div>' : '<div class="groupe-icon-status-open"><a data-toggle="tooltip" data-placement="bottom" data-original-title="Groupe Ouvert" title=""  href="#"> Ouvert</a></div>';	
    		
    		$donnees .= '<div class="col-md-4"><div class="box-groupe box-widget-groupe widget-all-groupe"><div class="preview-groupe-img"></div><div class="widget-groupe-header bg-image-groupe" style="background-image: url(' . $groupe->Groupe_FondBoxIMG($fetch[$g]['id']) . ');">' . $confidentialite_button . '<h3 class="widget-groupe-nom">' . $system->filtertext($fetch[$g]['name']) . '</h3><h5 class="widget-groupe-description">#' . $system->filtertext($fetch[$g]['name']) . '</h5><div class="groupe-icon-likes"><a data-toggle="tooltip" data-placement="bottom" data-original-title="' . $groupe->LikeToMember_Groupe($fetch[$g]['id']) . '" title="' . $groupe->LikeToMember_Groupe($fetch[$g]['id']) . '" href="#"> ' . $groupe->TotalLike_Groupe($fetch[$g]['id']) . '</a></div><div class="groupe-icon-users"><a data-toggle="tooltip" data-placement="bottom" data-original-title="Membres" title="Membres" href="#"> ' . $groupe->TotalMembre_Groupe($fetch[$g]['id']) . '</a></div></div>' . $confidentialite_status . '<div class="widget-groupe-image"><div class="groupe-profile-circle-box" style="background-image: url(' . $groupe->Groupe_AvatarIMG($fetch[$g]['id']) . ');"></div></div><div class="box-footer-groupe"> <ul class="list-unstyled-groupe team-info-groupe m-b-0"> <li><img src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="Avatar"></li><li><img src="https://bootdey.com/img/Content/avatar/avatar2.png" alt="Avatar"></li><li><img src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="Avatar"></li><li><img src="https://bootdey.com/img/Content/avatar/avatar2.png" alt="Avatar"></li><li><img src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="Avatar"></li></ul> <div class="row"> <div class="col-sm-12"><div class="description-block-groupe">' . $system->filtertext($groupe->DescriptionMaxi_Groupe($fetch[$g]['description'], 140, '...')) . '</div><a class="btn btn-social btn-linkedin btn-xs" href="' . PATH . '/groupe/' . $fetch[$g]['name'] . '/' . $fetch[$g]['id'] . '/" role="button">Voir le groupe</a> </div></div></div></div></div>';	
    		
    		}
    		
    echo json_encode([
    	'donnees' => $donnees
    ]);
    ?>

    j'ai essayer moi même de modifier le code comme le premier mais sans succès je n'y arrive plus '--' 
    pouvez vous m'aider si vous plait ? :) 

    sa serais super sympas de votre part.

    pour transformer la pagination et faire passer les donnees du php&html comme pour le filter ^^

    -
    Edité par Anonyme 22 juin 2018 à 10:31:47

    • Partager sur Facebook
    • Partager sur Twitter

    Pagination Ajax json php aide pour le HTML

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown