Angular scroll with problem loading BD data

Asked

Viewed 174 times

0

I am trying to implement Infinite Scroll to my project and following some lessons I found on the internet I reached this code:

<?php 
$query = "SELECT * FROM produtos ORDER BY id DESC";
$resultado = mysqli_query($conectar, $query);

while($linhas = mysqli_fetch_assoc($resultado)){ 
$imagem = pg.'/media/'.$linhas['imagem'];
$prod_nome = $linhas['nome'];
$prod_nome = str_replace(" ","-",$prod_nome);
$link_prod = pg.'/produto/'.$linhas['id'].'/'.$vid_nome;
?>

<div ng-controller="ContentsController" >
<div infinite-scroll="contents.nextPage()" infinite-scroll-distance="2" infinite-scroll-disabled="contents.busy">
    <span ng-repeat="content in contents.items">

<div id="{{content.id}}" class="col-sm-4 m-b-15" title="{{content.nome}}">
<div class="well well-sm">
    <div class="thumb-overlay">
        <a href="http://teste.com/{{content.id}}/{{content.nome}}">
            <div class="thumb-overlay">
                <img src="http://teste.com/{{content.imagem}}" id="{{content.imagem}}" class="img-responsive ">                                                         
            </div>
        </a>
        <div class="actions"></div>
    </div>
    <a href="http://teste.com/{{content.id}}/{{content.nome}}">
        <div class="title title-truncate">{{content.nome}}</div>
    </a>
    <div class="clearfix"></div>                                        
</div>
</div>
    </span>
</div>
</div>

<script>
(function(){

var myApp = angular.module('myApp', ['infinite-scroll']);
myApp.controller('ContentsController', function($scope, Contents) {
    $scope.contents = new Contents();
});

myApp.factory('Contents', function ($http) {
    var Contents = function(){
        this.items = [];
        this.busy = false;
        this.page = 1;
    }

    Contents.prototype.nextPage = function(){
        if(this.busy) return;
        this.busy = true;
        var url = 'http://teste.com/produtos?page='+this.page;

        $http.get(url).success(function(data){
            for (var i = 0; i < data.length; i++){
                this.items.push(data[i]);
            };
            this.page++;
            this.busy = false;
        }.bind(this));
    };
    return Contents;    
});
}).call(this);
</script>

my problem is that I can’t connect to the "products" table where the information is to be displayed. Can anyone tell me where and what I need to change to connect to the comic? Thank you.

  • It’s not like this: https://answall.com/questions/220227/comorepeg-fazer-um-splice-em-um-http-get-usando-ionic-angularjs-para-pesqui ?

  • @Ramos in my case is a page that lists all the data that is in the database.

2 answers

0

In View, something like on-Infinite:

 <ion-list class="list">
            <div class="spacer" style="width: 300px; height: 90px;"></div>
            <ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="onInfinite()" distance="5px" ng-if="hasMoreData"></ion-infinite-scroll>
        </ion-list>

        <ion-list class="list">
            <div class="item" ng-if="results.length == 0">
                <p>Nenhum resultado encontrado...</p>
            </div>
        </ion-list>


        <ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="10%">
            <ion-infinite-scroll-content loadingSpinner="bubbles">




    </ion-content>
    <!-- ./content -->
</ion-view>

And on the controller, something like:

// animation readmore
        var fetchItems = function () {
            for (var z = 0; z < fetch_per_scroll; z++) {
                if (angular.isObject(data_items[lastPush])) {
                    $scope.items.push(data_items[lastPush]);
                    lastPush++;
                } else {;
                    $scope.noMoreItemsAvailable = true;
                }
            }
            $scope.$broadcast("scroll.infiniteScrollComplete");
        };

EDITED:

And after the top function, the onInfinite function:

// event readmore
        $scope.onInfinite = function () {
            $timeout(fetchItems, 500);
        };

Follow a complete controller, at http.get I call the api that connects to the database:

$scope.scrollTop = function () {
            $ionicScrollDelegate.$getByHandle("top").scrollTop();
        };
        // open external browser 
        $scope.openURL = function ($url) {
            window.open($url, "_system", "location=yes");
        };
        // open AppBrowser
        $scope.openAppBrowser = function ($url) {
            window.open($url, "_blank", "closebuttoncaption=Done");
        };
        // open WebView
        $scope.openWebView = function ($url) {
            window.open($url, "_self");
        };

        // Set Motion
        $timeout(function () {
            ionicMaterialMotion.slideUp({
                selector: ".slide-up"
            });
        }, 300);
        // animation loading 
        $ionicLoading.show({
            template: '<div class="loader"><svg class="circular"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg></div>'
        });

        // Retrieving data
        var itemID = $stateParams.cadastra_oferta_cod_oferta;

        //    console.log('Abracadabra: ' + itemID);

        //    window.localStorage.setItem("fornecedor_temp", itemID);


        var current_item = [];
        if (window.localStorage.getItem("data_ofertass") !== "undefined") {
            var datas = JSON.parse(window.localStorage.getItem("data_ofertass"));
            for (var i = 0; i < datas.length; i++) {
                if ((datas[i].cadastra_oferta_cod_oferta === parseInt(itemID)) || (datas[i].cadastra_oferta_cod_oferta === itemID.toString())) {
                    current_item = datas[i];
                }
            }
            // event done, hidden animation loading
            $timeout(function () {
                $ionicLoading.hide();
                $scope.ofertas = current_item;
            }, 500);
        };

        if (!angular.isObject(current_item)) {
            var itemID = $stateParams.cadastra_oferta_cod_oferta;
            var current_item = [];
            $http.get("http://seusite_com_sua_api/admin/apis/api_listagem/lista_oferta_single_api.php?json=promocao").then(function (response) {
                // Get data single
                var datas = response.data;
                try {
                    window.localStorage.setItem("data_ofertass", JSON.stringify(datas));
                } catch (e) {
                    window.localStorage.clear();
                    window.localStorage.setItem("data_ofertass", JSON.stringify(datas));
                    $state.reload();
                    $scope.$state = $state;
                }
                for (var i = 0; i < datas.length; i++) {
                    if ((datas[i].cadastra_oferta_cod_oferta === parseInt(itemID)) || (datas[i].cadastra_oferta_cod_oferta === itemID.toString())) {
                        current_item = datas[i];
                    }
                }
            }, function (response) {
                // Error message
                var alertPopup = $ionicPopup.alert({
                    title: "error " + response.status,
                    template: response.statusText + "<br/>problem: table ofertas",
                });
            }).finally(function () {
                $scope.$broadcast("scroll.refreshComplete");
                // event done, hidden animation loading
                $timeout(function () {
                    $ionicLoading.hide();
                    $scope.ofertas = current_item;


                }, 500);
            });
        }
        $scope.doRefresh = function () {
            // Retrieving data
            window.localStorage.clear();
            var itemID = $stateParams.cadastra_oferta_cod_oferta;
            var current_item = [];
            $http.get("http://seusite_comapi/admin/apis/api_listagem/lista_oferta_single_api.php?json=promocao").then(function (response) {
                // Get data single
                var datas = response.data;
                window.localStorage.setItem("data_ofertass", JSON.stringify(datas));
                for (var i = 0; i < datas.length; i++) {
                    if ((datas[i].cadastra_oferta_cod_oferta === parseInt(itemID)) || (datas[i].cadastra_oferta_cod_oferta === itemID.toString())) {
                        current_item = datas[i];
                    }
                }
            }, function (response) {
                // Error message
                var alertPopup = $ionicPopup.alert({
                    title: "error " + response.status,
                    template: response.statusText + "<br/>problem: table ofertas",
                });
            }).finally(function () {
                $scope.$broadcast("scroll.refreshComplete");
                // event done, hidden animation loading
                $timeout(function () {
                    $ionicLoading.hide();
                    $scope.ofertas = current_item;
                }, 500);
            });
        };



        //add to cart function
        $scope.addToCart = function (id, image, name, price, supply_id, deliver, tipopag, entrega) {
            // CHAMA CART.ADD DE SERVICES 
            window.localStorage.setItem("fonecedor_carrinho", supply_id);
            window.localStorage.setItem("tipos_pagamentos", tipopag);
            window.localStorage.setItem("frete", deliver);
            window.localStorage.setItem("faz_entrega", entrega);


            console.log("ID Fornecedor: " + supply_id);

            cart.add(id, image, name, price, 1, supply_id, deliver);

            $ionicHistory.nextViewOptions({
                disableAnimate: true,
                disableBack: true
            });

            var adiciona = '1';
            window.localStorage.setItem("vazio", adiciona);

            $state.go("nhaac.carrinho");

        };

        // FAVORITAR
        $scope.addFavorite = function (id, image, name, supply_id) {


            // COLOCA TEMPORARIAMENTE EM LOCALSTORAGE
            window.localStorage.setItem("favorita_cod_oferta", id);
            window.localStorage.setItem("favorita_image", image);
            window.localStorage.setItem("favorita_oferta", name);
            window.localStorage.setItem("favorita_cod_fornecedor", supply_id);


            // PEGA DO LOCALSTORAGE E CRIA UM CAMPO

            $scope.f_cod_fornecedor = window.localStorage.getItem("favorita_cod_fornecedor");

            $scope.f_image = window.localStorage.getItem("favorita_image");

            $scope.f_oferta = window.localStorage.getItem("favorita_oferta");

            $scope.f_cod_oferta = window.localStorage.getItem("favorita_cod_oferta");

            $scope.cod_cliente = window.localStorage.getItem("cod_cliente");

            $ionicLoading.show();

            var url = "?cod_cliente=" + $scope.cod_cliente + "&cod_fornecedor=" + $scope.f_cod_fornecedor + "&imagem=" + $scope.f_image + "&oferta=" + $scope.f_oferta + "&cod_oferta=" + $scope.f_cod_oferta + ""
            console.log(url);


            var encodedurl = encodeURI(url);

            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var responseishere = xmlhttp.responseText;
                    console.log(responseishere);
                    var myobj = JSON.parse(responseishere);
                    alert(myobj.message);
                    $ionicLoading.hide();
                } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
                    alert("Server Error");
                    $ionicLoading.hide();

                }
            };
            xmlhttp.open("GET", "http://vovocooks.com.br/admin/apis/put/favorita.php" + encodedurl, true);
            xmlhttp.send();

            alert("Hummm, que delícia! Favoritado com sucesso.");

            $state.go("nhaac.favoritos")

            // DELETA DO LOCALSTORAGE E CRIA UM CAMPO

            window.localStorage.removeItem("favorita_cod_oferta", id);
            window.localStorage.removeItem("favorita_image", image);
            window.localStorage.removeItem("favorita_oferta", name);
            window.localStorage.removeItem("favorita_cod_fornecedor", supply_id);
        };

        $scope.ChamaAvalia = function (vovo) {
            window.localStorage.setItem("cod_vovo_pedido", vovo);
            $state.go('nhaac.listaavalia');


        };

        var tipo = '';

        // $scope.checarPermissoes();

        $scope.checarPermissoes = function (tipo) {
            var permitido;

            if (tipo === 'logado_usuario' && window.localStorage.getItem("user_log") !== null) {
                permitido = true;
            } else {
                permitido = false;
            }

            return permitido;
        };




        // animation ink (ionic-material)
        ionicMaterialInk.displayEffect();
        $scope.rating = {};
        $scope.rating.max = 5;
    })
  • If not, edit your question by putting your PHP....

  • could you tell where the code above brings up the data from the BD table? Thank you

  • I’ll edit to show...

  • includes the php you were using before you started studying this method

0

Your PHP, try turning it into a JSON, like this example. The way you’re doing, I don’t know if you get the results.

<?php


header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

include 'database.php';

//$cod_vovo=$_GET['cod_vovo'];


$query="SELECT 
   cod_avaliacao,
   cod_cliente,
   cod_fornecedor,
   AVG(avaliacao_geral)
FROM
   avaliacao 
GROUP BY cod_fornecedor";


$result=$con->query($query);

$row_cnt = mysqli_num_rows($result);
if ($result->num_rows > 0) 
{
    $count=0;
    echo "[";
    while($row = $result->fetch_assoc()) 
    {
            $count++;
            echo json_encode($row);

            if($count!=$row_cnt)
            {
                    echo ",";
            }


    }
    echo "]";
}
else
{
echo "error";
}

?>
  • to my unhappiness I am not able to incorporate, you would have some more instantaneous way that you can heal my doubts?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.