How to pull content via AJAX from a site that has a menu header and a fixed audio player?

Asked

Viewed 1,924 times

5

How can I create a website that uses AJAX for loading the pages ?

What is the best way to do this without bugs occurring and that are really functional?

I have plans to create some websites that have a player de áudio, which cannot stop when a person goes to another page.

Example site: http://www.nandolocutor.com/

I would like to create a site similar to this.

On the page would be something similar to that:

<body>
    <div class="meu-player">Aqui fica o player</div>
    <div class="meu-menu">Aqui fica o menu</div>
    <section>Aqui fica o conteúdo que é puxado via ajax e exibido</section>
</body>

I would like to receive functional examples (in code) of how to do this.

  • 1

    You can split the site into divs, sections or any other tag, putting the audio player in one and loading the contents in another, so the player will never stop playing.

  • Thank you @Patrick could you turn your comment into a reply? you could also put in your question the code required for such functionality.

  • any restrictions to frameworks? like angular or knockout?

2 answers

8

You can split the site into several parts:

HTML

<head>
    <!-- Sempre importe as bibliotecas antes de tentar trabalhar com elas. -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
       // Checa se a página foi carregada para evitar aplicar os códigos antes de ter algum elemento não carregado. Pode-se usar também "$(function(){".
        $(document).ready(function(){
            $("#home").on("click", function(){
                $("main").empty(); //Limpa para poder colocar o conteúdo.
                $("main").load("home.html"); //Faz uma requisição http para o servidor.
            });
            $("#sobre").on("click", function(){
                $("main").empty();
                $("main").load("sobre.html");
            });
        });
    </script>
</head>
<body>
    <!-- No caso, o header é a parte fixa, que não muda. -->
    <header>
        <div>"Aqui fica o player de audio."</div>
        <ul>
            <li id="home">Home</li>
            <li id="sobre">Sobre</li>
        </ul>
    </header>
    <main>
        <!-- Aqui é onde o conteúdo vai ser carregado. -->
    </main>
</body>

Remember that this only works if you have a server, the browser does not allow to do this kind of thing directly in the file system.

  • 3

    @Alexandrelopes window.history.pushState("objeto ou string", "Titulo", "/url");

  • Hello @Diegovieira thanks for the attentiveness! Still can not, is working only on my computer, when I host does not work. I don’t know what could have caused this. I’m going to host you now in some accommodation just so you can see how you are.

  • @Alexandrelopes Check through the browser console if you are returning an error, it is a good way to find out what is happening.

  • Yes, there is an error on line 12: http://i.imgur.com/Cfs9drt.png

  • Do the following, where this writing href and title put like this, "href", "title" respectively, missing added quotes.

  • @Alexandrelopes updated my answer with the correct code

  • Great! You did it! You only have a small bug. When you click on a link you are alone Aqui fica o inicio do meu site only what is inside the page home.html which in this case is a <h1>, fixing this gets show! Very good!

  • Got 100%, very good! How to use another tag, as for example <data-value> instead of <title> ? :D

  • @Alexandrelopes in html would be, <a data-value="algo"></a>, Jquery would stay $(this).data('value'); With tag you can do so var texto = $("data-value").html();

  • Oops, I meant to say data-value="Aqui fica o título"

  • @Alexandrelopes I will add one more example for you to understand the use.

Show 6 more comments

7


To change the page URL without compromising the content (refresh) just use the following code.

Javascript

window.history.pushState("objeto ou string", "Titulo", "/url");

DEMO of the above working code

HTML Adapted with the code of @Patrick.

<head>
    <!-- Sempre importe as bibliotecas antes de tentar trabalhar com elas. -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
       // Checa se a página foi carregada para evitar aplicar os códigos antes de ter algum elemento não carregado. Pode-se usar também "$(function(){".
        $(document).ready(function(){
            $(".ajax").on("click", function(e){
                e.preventDefault(); //eliminamos o evento
                var path = $(this).attr("href"); //Pegamos o caminho
                var titulo = $(this).attr("title"); //pegamos o titulo da página
                document.title = titulo; // Alterar o titulo da página
                window.history.pushState("", titulo, path);   
                $("main").empty(); //Limpa para poder colocar o conteúdo.
                $("main").load(path); //Faz uma requisição http para o servidor.
            });
        });
    </script>
</head>
<body>
    <!-- No caso, o header é a parte fixa, que não muda. -->
    <header>
        <div>"Aqui fica o player de audio."</div>
        <ul>
            <li><a href="home.html" class="ajax" title="Meu site">Home</a></li>
            <li><a href="sobre.html" class="ajax" title="Meu site - Sobre">Sobre</a></li>
        </ul>
    </header>
    <main>
        <!-- Aqui é onde o conteúdo vai ser carregado. -->
    </main>
</body>

To use the parameter data- and recover the value with JQuery you must use the $.data

Jquery

$(function(){
    var texto;

    //Recuperar do data-value
    texto = $('a.value').data('value');
    $('.resultado').append('<li>' + texto + '</li>');

    //Recuperar do data-titulo
    texto = $('a.titulo').data('titulo');
    $('.resultado').append('<li>' + texto + '</li>');

    //Recuperar do data-target
    texto = $('a.target').data('target');
    $('.resultado').append('<li>' + texto + '</li>');

    //Recuperar do data-meuVar
    texto = $('a.meuVar').data('meuvar');
    $('.resultado').append('<li>' + texto + '</li>');
});

This is my HTML for example

HTML

<a href="#" class="value" data-value="texto do data-value"></a>

<a href="#" class="titulo" data-titulo="texto do data-titulo"></a>

<a href="#" class="target" data-target="texto do data-target"></a>

<a href="#" class="meuVar" data-meuvar="texto do data-meuvar"></a>

<ul class="resultado"></ul>

This code will show list

  • date-value text
  • title date text
  • text of the date-target
  • text of the date

You can follow the code working on this DEMO

  • 1

    @Alexandrelopes can leave

  • I tested and there were problems. Opening on my PC works cool, only if I host it no longer works. What may be?

  • @Alexandrelopes, connected the server?

  • What do you mean? I don’t understand.

  • How to fix the title part? I saw that the tag was used <title> only it’s not working.

  • @Alexandrelopes updated the code, but the title it will take from the parameter title of href.

  • Hello @Diegovieira check it out: http://player.esy.es/, I got it, it got really good! Oh! and thanks for everything, you were very attentive and very cool! Vlw...

  • 1

    Please, we are all here to help, I believe that the score is a way of thanking, having the best answer or not, I am happy to solve your problem. Good luck on the project!

  • Just a basic "little doubt": When a person enters http://player.esy.es/ the menu appears, if they click on a link the content is loaded, for example if I click on About it pulls the content of sobre.html, but if the person directly accesses sobre.html the menu does not appear. On the site I gave example appears. Thanks and apologies again... :/

  • 1

    This happens because with this structure you are loading it into a div, you can resolve it differently, all pages contain the menu and not just the text.

  • And how do I make .load pull only determined div within the requested page ? Ex <div id="puxa">Irá puxar só o que tiver aqui dentro</div>

  • That way I can put the menu on all pages and when the person clicks on a link does not duplicate the same menu.

  • load on the body, create a div main where you will always receive these pages with the menu, so the change happens changing the whole structure of the page.

Show 8 more comments

Browser other questions tagged

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