Infinite scroll no foreach

Asked

Viewed 187 times

0

Could someone help me? I’m trying to find some way to use Infinite scroll in this code:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "lista.m3u8");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

if (substr($info["http_code"], 0, 2) != 20) {
    die("Não possível conectar ao servidor!");
}

preg_match_all('/(tvg-logo="(?<logo>.*?)".+group-title="(?<name>.*?)".+\n(?P<link>http?:\/\/.+))/', $response, $channels, PREG_SET_ORDER);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>nPlay</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://mdbootstrap.com/previews/docs/latest/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://mdbootstrap.com/previews/docs/latest/css/mdb.min.css" rel="stylesheet">
    <style>
    footer{
        background-color:#1F2024;
        color: #fff;
        font-size: 10px;
    }
    body{
        background-color: #171818;
    }

    .secondbase {
        background-color: rgba(255,255,255,.6); 
        margin-top: -90px;
    }
    .list-group-item {
        border:none;
        background-color: #171818;
        float: left;
        height: 240px;
        padding: .5rem .25rem;
        width: 150px;
    }

    .list-group-item img {
        border:none;
        height: 200px;
        width: 140px;
        padding: .5rem .25rem;

    }

    #modal iframe {

        border:none;
        height: 100%;
        width: 100%;
    }

    .modal-dialog {
  width: 100%;
  height: 100%;
  padding: 0;
    }

    .modal-content {

        background-color: #16171A;
  height: 90%;
  width: 90%;
  border-radius: 0;
    }

    .modal-body {

        height: 84%
    }

    .navbar {
        background-color: #1F2024;
    }

    img{border-radius: 10px;}

    #info_bar{
        color: #fff;
        font-size: 10px;
        text-align: center;
    }

    </style>
</head>
<body>
<header>
    <nav class="navbar navbar-expand-lg fixed-top">
        <a class="navbar-brand">nPlay</a>
    </nav>
</header>


<div class="py-4"></div>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <ul id="channels-list">               
                    <?php foreach($channels as $channel): ?>
                    <li class="list-group-item">
                        <a href="<?php echo $channel["link"] ?>" title="<?php echo $channel["name"] ?>">
                            <img src="<?php echo $channel["logo"] ?>" class="img-responsive img-circle" />
                            <div id="info_bar">
                              <?php echo $channel["name"] ?>
                            </div>
                        </a>

                    </li>

                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<hr>
<footer class="fixed-bottom">
    <div class="text-center "></footer>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://mdbootstrap.com/previews/docs/latest/js/bootstrap.min.js"></script>
<script src="https://mdbootstrap.com/previews/docs/latest/js/mdb.min.js"></script>
<script src="https://mdbootstrap.com/previews/docs/latest/js/jarallax.js"></script>
<script src="https://mdbootstrap.com/previews/docs/latest/js/jarallax-video.js"></script>
<script>
    new WOW().init();

    $("#channels-list a").click(function(e) {
        e.preventDefault();

        $("#modal").find(".modal-title").text( $(this).attr("title") );
        $("#modal").find(".modal-body")
            .empty()
            .append( "<iframe allowFullScreen='allowFullScreen' allowscriptaccess='always' src=\""+$(this).attr("href")+"\"></iframe>" ); //Altere essa linha para chamar outro arquivo

        $("#modal").modal("show");
    });

</script>



<div class="modal fade" tabindex="-1" role="dialog" id="modal" data-backdrop="static">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">%channel_name%</h4>
      </div>

      <div class="modal-body"></div>

      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

</body>
</html>
  • With this code you will not be able to. It is necessary to split the file lista.m3u8 in several pieces and only then use AJAX to create the infinite scroll effect.

  • Okay, I’ll try to do it here. Taking advantage that the code is yours... when I close the modal the audio video continues playing, as I could close right?

  • It is necessary to use the event $('#myModal').on('hidden.bs.modal') to destroy the <iframe> created at the opening.

1 answer

0


As I commented earlier, it is necessary to separate PHP from HTML. In this case we will create a file called loadChannels.php, with the following code:

<?php

header("Access-Control-Allow-Origin: *");

/* Captura a página */
if (isset($_GET['page'])) {
    $page = (int)$_GET['page'];
} else {
    $page = 1;
}

/* Acessa o parquivo `lista` + número da página + `.m3u8` */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8081/lista{$page}.m3u8");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

if (substr($info["http_code"], 0, 2) != 20) {
    die();
}

preg_match_all('/(tvg-logo="(?<logo>.*?)".+group-title="(?<name>.*?)".+\n(?P<link>http?:\/\/.+))/', $response, $channels, PREG_SET_ORDER);

/**
 * Cria a lista LI e escreve na tela.
 * Como vamos acessar via AJAX, o conteúdo
 * será retornado via JavaScript
 */
foreach($channels as $channel): ?>
<li class="list-group-item">
    <a href="<?php echo $channel["link"] ?>" title="<?php echo $channel["name"] ?>">
        <img src="<?php echo $channel["logo"] ?>" class="img-responsive img-circle" />
        <div id="info_bar">
          <?php echo $channel["name"] ?>
        </div>
    </a>
</li>
<?php endforeach; ?>

Now in the HTML file, we can use the following Javascript:

/* Define a página inicial */
let scrollPage = 1;

/* Cria uma função para detectar se o usuário rolou a barra até o final */
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       loadChannels();
   }
});

/* Utilizamos o método `on` para detectar o evento de clique de novos elementos */
$("#channels-list").on("click", "a", function(e) {
    e.preventDefault();

    $("#modal").find(".modal-title").text( $(this).attr("title") );
    $("#modal").find(".modal-body")
        .empty()
        .append( "<iframe allowFullScreen='allowFullScreen' allowscriptaccess='always' src=\""+$(this).attr("href")+"\"></iframe>" ); //Altere essa linha para chamar outro arquivo

    $("#modal").modal("show");

    /*
     * Utilizamos esse evento para executar uma função ao fechar o modal
     * Caso o modal seja fechado sem remover o `iframe`, o player continuará funcionando.
     */
    $('#modal').on('hidden.bs.modal', function (e) {
      $("#modal iframe").remove();
    })
});

/*
 * Utilizamos esse evento para executar uma função ao fechar o modal
 * Caso o modal seja fechado sem remover o `iframe`, o player continuará funcionando.
 */
$('#modal').on('hidden.bs.modal', function (e) {
  $("#modal iframe").remove();
})

/**
 * Função responsável por realizar a requisição para `loadChannels.php`
 */
function loadChannels(page) {

    /* Realizamos a requisição e retornamos o resultado na variável `data` */
    $.get("loadChannels.php?page="+scrollPage, function(data) {

        /* Incrementamos o valor retornado na DIV indicada e somamos o valor de `scrollPage` + 1 */
        $("#channels-list").append(data);
        scrollPage++;
    });
}

/* Carregamos a primeira lista */
loadChannels();

It is necessary to remove the code from the DIV #channels-list

  • Show! The infinite scroll worked. But the modal didn’t work.

  • @Welderandradeserute updated the answer

  • It worked! Just one more thing if it’s not too much trouble...I need to get the name of the movie in the list, in the function preg_match_all is doing this but the name is after group-title separated by a single comma, as I do?

  • #EXTINF:-1 tvg-logo="https://i.imgur.com/Jp4tiwd.jpg" group-title="Vod! Ondemand!" ,Viva: A Vida é um Festa (Dublado) - 2018 - 720p http://cdn1.ntcdn.us/content/httpdelivery/filmes2018/COCO2017DUB-ALTO.mp4

  • @Welderandradeserute If possible, create another question, as this question escapes from the main subject and this can lead moderators to close this question. Anything, just mark me in the question comment box.

Browser other questions tagged

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