Browser "back and forth" button and dynamic div without refresh

Asked

Viewed 1,039 times

0

Me and a friend have been having some problems with jQuery..
If we base it on a code to make the button back and forth of the browser work on our site, with the function of a update div without refresh...
The code is working in parts, but I’m having to deal with the following errors:
1º When I enter page 1, then page 2 and try to go back through the browser arrow, the content, site title and url.
Follows the code:

<?php
$isXHR = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) === 'XMLHTTPREQUEST';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Inicio</title>
<script src="jquery.min.js"></script>
<script>
$(function () {
    var load = function (url) {
        $.get(url).done(function (data) {
			var title =  $(data).filter('title').text();
			$("title").html(title);
            $("#content").html(data);
        })
    };

    $(document).on('click', 'a', function (e) {
        e.preventDefault();

        var $this = $(this),
            url = $this.attr("href"),
            title = title;

        history.pushState({
            url: url,
            title: title
        }, title, url);

        document.title = title;

        load(url);
    });

    $(window).on('popstate', function (e) {
        var state = e.originalEvent.state;
        if (state !== null) {
            document.title = state.title;
            load(state.url);
        } else {
			//var title =  $(state).filter('title').text();
            //document.title = title;
            $("#content").empty();
        }
    });
});
</script>
</head>

<body>
<?php
if (!$isXHR) {
echo "
<ul>
	<li><a href=\"index.php\">Inicio</a></li>
	<li><a href=\"abc.php\">Página 2</a></li>
	<li><a href=\"abc2.php\">Página 3</a></li>
</ul>
";}
?>
<div id="content">Página 1</div>

</body>
</html>

abc.php (page 2)

<?php
$isXHR = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) === 'XMLHTTPREQUEST';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página 2</title>
<script src="jquery.min.js"></script>
<script>
$(function () {
    var load = function (url) {
        $.get(url).done(function (data) {
			var title =  $(data).filter('title').text();
			$("title").html(title);
            $("#content").html(data);
        })
    };

    $(document).on('click', 'a', function (e) {
        e.preventDefault();

        var $this = $(this),
            url = $this.attr("href"),
            title = title;

        history.pushState({
            url: url,
            title: title
        }, title, url);

        document.title = title;

        load(url);
    });

    $(window).on('popstate', function (e) {
        var state = e.originalEvent.state;
        if (state !== null) {
            document.title = state.title;
            load(state.url);
        } else {
			//var title =  $(state).filter('title').text();
            //document.title = title;
            $("#content").empty();
        }
    });
});
</script>
</head>

<body>
<?php
if (!$isXHR) {
echo "
<ul>
	<li><a href=\"index.php\">Inicio</a></li>
	<li><a href=\"abc.php\">Página 2</a></li>
	<li><a href=\"abc2.php\">Página 3</a></li>
</ul>
";}
?>
<div id="content">Página 2</div>
</body>

abc2.php (page 3)

<?php
$isXHR = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) === 'XMLHTTPREQUEST';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página 3</title>
<script src="jquery.min.js"></script>
<script>
$(function () {
    var load = function (url) {
        $.get(url).done(function (data) {
			var title =  $(data).filter('title').text();
			$("title").html(title);
            $("#content").html(data);
        })
    };

    $(document).on('click', 'a', function (e) {
        e.preventDefault();

        var $this = $(this),
            url = $this.attr("href"),
            title = title;

        history.pushState({
            url: url,
            title: title
        }, title, url);

        document.title = title;

        load(url);
    });

    $(window).on('popstate', function (e) {
        var state = e.originalEvent.state;
        if (state !== null) {
            document.title = state.title;
            load(state.url);
        } else {
			//var title =  $(state).filter('title').text();
            //document.title = title;
            $("#content").empty();
        }
    });
});
</script>
</head>

<body>
<?php
if (!$isXHR) {
echo "
<ul>
	<li><a href=\"index.php\">Inicio</a></li>
	<li><a href=\"abc.php\">Página 2</a></li>
	<li><a href=\"abc2.php\">Página 3</a></li>
</ul>
";}
?>
<div id="content">Página 3</div>
</body>
</html>

About possible duplicate... this way that you inform, can not return the content with the arrow of the browser. Nor did they give a specific answer.

  • 1

    Possible duplicate -> https://answall.com/questions/276897/problemas-com-jquery

  • 1

    Possible duplicate of Problems with Jquery

1 answer

1


First of all, your code has a lot of problems. One of them is that when the user clicks several times, the code only increases the number of requests. Ex:

The user enters the site and clicks 5 times on any of the links, instead of generating 5 requests, the code is generating 31 requests.

The problem is you’re adding whole the content in div#content. This makes the code Javascript is repeated countless times, generating errors and perhaps the bug "informed" in the question.

There are two ways to fix this:

  • Using the parseHTML to turn the answer into HTML. That way we’ll use find to capture our element (instead of adding the whole page). All of this in the Javascript
function load (url, container = "div#content") {
    $.get(url).done(function (data) {
        let content = jQuery( "<div>" ).append( jQuery.parseHTML( data ) );
        let title =  $(content).find("title").text();

        $("title").html(title);
        $("#content").html($(content).find(container));
    })
};
  • Informing what should be rendered (using the PHP and the header HTTP_X_REQUESTED_WITH as a basis).
<?php
$isXHR = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) === 'XMLHTTPREQUEST';
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Página 2</title>
        <?php if (!$isXHR) { ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
         /* Código JS aqui */
        </script>
    </head>

    <?php } ?>
    <body>
    <?php if (!$isXHR) { ?>
    <?php
    echo "
    <ul>
        <li><a href=\"index.php\">Inicio</a></li>
        <li><a href=\"abc.php\">Página 2</a></li>
        <li><a href=\"abc2.php\">Página 3</a></li>
    </ul>
    ";}
    ?>
    <div id="content" data-title="Título da página dois">Página 2</div>
    </body>
</html>

Preferably choose amendments with JS.

Another thing, throw it all in a file Javascript. It may sound silly or it’s just because you’re testing, but it’s hard to work with multiple codes identical, sometimes you correct the mistake in one and do not realize that you have forgotten others.

I added some comments to the code.

$(function () {
    function load (url, callback, container = "div#content") {
        $.get(url).done( data => {
            let content = jQuery( "<div>" ).append( jQuery.parseHTML( data ) );
            let title =  $(content).find("title").text();

            document.title = title;

            $("title").html(title);
            $("#content").html($(content).find(container));

            /**
             * Verifica se a variável callback é função
             * Caso seja, retorna true (sucesso)
             */
            if ( (typeof callback) == "function" ) {
                callback(true);
            }

        }).fail( () => {

            /**
             * Verifica se a variável callback é função
             * Caso seja, retorna false (falha)
             */
            if ( (typeof callback) == "function" ) {
                callback(false);
            }
        })
    };

    $(document).on('click', 'a', function (e) {
        e.preventDefault();

        /**
         * Carrega a URL a depender do resultado manipula o histórico
         * Ou exibe um lerta
         */
        load($(this).attr("href"), (result) => {
            if (result) {
                /**
                 * Na lógica de programação, você deve ter sucesso ou falha
                 * em algo para exibir uma mensagem ou alterar algum
                 * outro elemento da página
                 */
                history.pushState({
                    url: $(this).attr("href"),
                    title: $("title").text()
                }, $("title").text(), $(this).attr("href"));
            } else {
                alert("Fail");
            }
        });
    });

    $(window).on('popstate', function (e) {

        console.log( e.originalEvent.state );

        let state = e.originalEvent.state;
        if (state !== null) {
            document.title = state.title;
            load(state.url);
        }
    });

    /* Adiciona a primeira página no histórico */
    history.pushState({
        url: window.location.href,
        title: $("title").text()
    }, $("title").text(), window.location.href);
});

Is the code 100%? No. But I’ll leave it to you.

  • Man, thank you so much for everything!

  • Thanks for taking a little bit of your time to help people you don’t even know, if you need me for anything, even though it’s not a big deal... you can count on me! facebook.com/er1cckz

  • Done! I gave positive feedback.

  • Valdeir on the requisitions of the first code, it worked perfectly! but still we still have problems with the system in the matter of returning page twice, we looked for some topics here at Stackoverflow to see if we could without having to reopen the current topic, but I did not find anything that could solve, you were the only person who managed to give me a possible salvation so far, how can I proceed?

  • 1

    @Erickpereira I edited the JS code just now, if possible copy and paste and test again. I did a test on localhost and apparently it worked.

  • I will do a test on the localhost, anything I return, I appreciate the attention from now!

  • It worked, I thank you from my heart! <3

Show 2 more comments

Browser other questions tagged

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