Navigation without a refresh!

Asked

Viewed 5,281 times

6

I’m developing a website that has a div where I have a script that lists results of an SQL query. These are images, in this case. The site was developed on just one page, so by clicking on the portfolio, it just takes me to div #portifolio. The problem is that I would like to change the category on portfolio that he didn’t give refresh on the page, only the div.

I already searched a lot on the net, I even found a script that was very similar to what I wanted, but gave bug in modal window and effect Grayscale also.

The code is this:

<div id="portifolio" class="grid_24">
 <nav id="menu-portifolio" class="grid_24"> 
     <ul id='nav'>
                            <li><a href='#'>SERVIÇOS<img class='icon-menu' src='images/icon-menu.png' alt='Icone do menu'/></a>
                                <ul>
                                    <?php
                                        // Includa a conexão com o banco de dados sql
                                        include "conn.php";

                                    // Conecta a tabela categorias
                                        $result = mysql_query('SELECT * FROM categorias')or die(mysql_error());

                                        echo "<li><a href='?id_todos=todos#bloco03'> &nbsp Todos </a></li>";

                                        // Exibe o resultado da consulta
                                        while ($row = mysql_fetch_object($result)) {
                                            echo "<li>      
                                                    <a href='?id=$row->id#bloco03'> &nbsp $row->nome </a>
                                                  </li>
                                               ";
                                        }                           
                                    ?> 
                              </ul>
                            </li>                                
                         </ul>
                    </nav>  

                </nav>

                <!--  Primeira pagina portifólio -->
                <div id="modal" class="conteudo-portifolio grid_24">                     
                        <?php 

                        // Conecta a tabela portifolio                          
                        if (isset($_GET['id']) && is_numeric($_GET['id'])) {  
                            $id_categoria = $_GET['id']; 
                            $resultado = mysql_query("SELECT * FROM portifolio WHERE id_categoria = '$id_categoria' LIMIT 12"); 

                            // Exibe o resultado da consulta
                            $myModal = 1;
                            while ($row = mysql_fetch_object($resultado)){
                                    echo "
                                        <figure class='img-portifolio'> 
                                            <a href='#janela1".$myModal."' rel='modal'><img class='' src=". $row->imagem ." alt=". $row->titulo ."/></a>
                                        </figure>

                                        <div class='window' id='janela1".$myModal."'>
                                            <img class='img-thumb' src=". $row->imagem ." alt=". $row->titulo ."/>
                                        </div>                           

                                        <!-- mascara para cobrir o site -->  
                                        <div id='mascara'></div>                                        

                                         ";
                                $myModal++;
                                }                               
                            } else {
                                $resultado_todos = mysql_query("SELECT * FROM portifolio LIMIT 12");
                                // Exibe o resultado da consulta
                                $myModal = 1;
                                while ($row = mysql_fetch_object($resultado_todos)){
                                    echo "
                                        <figure class='img-portifolio'> 
                                            <a href='#janela1".$myModal."' rel='modal'><img class='' src=". $row->imagem ." alt=". $row->titulo ."/></a>
                                        </figure>

                                        <div class='window' id='janela1".$myModal."'>
                                            <img class='img-thumb' src=". $row->imagem ." alt=". $row->titulo ."/>
                                        </div>                           

                                        <!-- mascara para cobrir o site -->  
                                        <div id='mascara'></div>                                        

                                         ";
                                $myModal++;
                                }
                            }                                   

                        ?>
                    </div>

                </div>

                </div>

And this is jQuery:

        <script type="text/javascript">
        $(document).ready(function(){
            var content = $('#portifolio');

            //pre carregando o gif
            loading = new Image(); loading.src = 'images/loading_ajax.gif';
            $('#portifolio a').live('click', function( e ){
                e.preventDefault();
                content.html( '<img src="images/loading_ajax.gif" />' );

                var href = $( this ).attr('href');
                $.ajax({
                    url: href,
                    success: function( response ){
                        //forçando o parser
                        var data = $( '<div>'+response+'</div>' ).find('#portifolio').html();

                        //apenas atrasando a troca, para mostrarmos o loading
                        window.setTimeout( function(){
                            content.fadeOut('slow', function(){
                                content.html( data ).fadeIn();
                            });
                        }, 500 );
                    }
                });

            });
        });
    </script>
  • 1

    Can you put an example of your code here? The part of the ajax call and the code of the link that calls ajax makes all the difference to be able to answer.

  • I put the code!

  • PHP code and HTML/jQuery are in the same file?

  • Yes! All in the index.

  • 2

    Nostalgia MVC :) $id_categoria = $_GET['id']; - Off: Be careful with lines where you take what the user sends and send directly to the database. I recommend a read of this article.

3 answers

2

Create another page with the content you want to upload and then use it to upload the data.

This makes it more organized and faster, since less data will be transferred. You can also simplify javascript a little by using the function .load:

content
.fadeOut('slow')
.load('ajax.php?href=' + href, function () {
  content.fadeIn();
});
  • Well, I don’t quite understand since the site is one-page only?

  • The part you will update leave separate. Include it on the main page. The user will not know that there are two pages, but, by the organization, it is.

  • Um.. ah got it.. I’ll test here then and then tell me if it worked.

  • It worked almost everything mate. T appearing only the div as I wanted, but I can’t open the lightbox anymore :s what will be that can be?

  • When you load something via ajax you have to alert the plugins that there are new elements, update them. This will vary with the plugin you are using.

  • @Hermesnetto, as you are to replace the elements of #portfolio you need to reset the events too, or delegate the click. Try so: $('#portifolio').delegate('a', 'click', function(e){

Show 1 more comment

1


Follow an example of using ajax with jquery.

<!-- Incluo o jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

<!-- Script para efetuar as requisições -->
<script>
$(document).ready(function(){
    $("a").click(function(){
        link = $(this).attr("href");
        $.ajax({
           url : link,
           dataType : "HTML", // Pode ser SCRIPT se o retorno for somente comandos JavaScript
           type : "GET", // Pode ser get ou post..
           success : function(conteudo){
                $("#CONTEUDO").html(conteudo);
           },
           error : function(a,b,c){
                 alert("Erro : "+a["status"]+" "+c);
           }
        });
    });
});
    </script>


<!-- Um link para testar a requisição -->
<a href="teste.php?nome=teste" />AJAX</a>
<!-- DIV que vai receber as informações -->
<div id="CONTEUDO"></div>

Now the file php test.

<?php
   echo "Hello world <b>".$_GET["nome"]."</b>";
?>

0

Instead of answering how to make a simple feature, if you really want to do this, you’d better invest in specialized libraries. Would indicate Angularjs, Backbonejs, Canjs and Ember.

In a way similar to how a CRUD could be done on the server side, these libraries are excellent as they help to make practically one MVC on the client side.

Here is a functional example of a All of you in a room. The rest also have something similar.

Important note: When using Javascript to build your HTML, be careful not to make your page inaccessible. Screen readers may not understand what’s going on. It’s possible to turn Ajax into accessible pages but it’s more complicated. Read more about WAI ARIA.

  • My experience with this came down to "very limited, very heavy, kind of unnecessary (even more for one page)". I became interested in it after I realized that in larger projects I started to reinvent the wheel: there are tutorials or articles about MVC in Portuguese?

  • Well, about Angular has at least this http://tableless.com.br/criando-aplicacao-simples-angularjs/, but Google has more. As for being too heavy for one page, well, it depends on whether it’s just for one page. If it is, a simple custom code will do. Now, anything more complex is worth using libraries like the ones I indicated.

  • I already tried using Angular, gave up after I saw that it is not possible to use "sub-views", something I needed in the project. What interests me most about MVC at the moment are the concepts: from the moment I started writing functions that simulate "providers" I saw that I needed to use something like this. Libraries require a template from you, hindering (a little) the "sub-views" in favor of other templates, for example.

Browser other questions tagged

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