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

0

Me and a friend are having some problems with jQuery ..
If we rely on a code to make the back and forth button of the browser work on our site, with the function of a div refresh without refresh ...
The code is working in parts, however I am having to deal with the following errors:
1st When I enter page 1, then page 2 and try to return through the browser arrow, the content, title of the site and url buga. Home Here is 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 you inform, you can not return the content with the arrow in the browser. They also did not give a specific answer.

    
asked by anonymous 17.02.2018 / 03:18

1 answer

1

To begin with, your code has a lot of problems. One is that when the user clicks multiple 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 that you are adding everything content in div#content . This causes the JavaScript tag to be repeated countless times, generating errors and perhaps the "bug" in the question.

There are two ways to fix this:

  • Using parseHTML to transform the response into HTML >. That way we'll use find to capture our element (instead of adding the whole page). All this in 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 PHP and the HTTP_X_REQUESTED_WITH header as the base).
<?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ódigoJSaqui*/</script></head><?php}?><body><?phpif(!$isXHR){?><?phpecho"
    <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 the changes with JS.

Another thing, play it all inside a JavaScript file. It may sound silly or just because you're testing, but it's hard to work with multiple identical codes, sometimes you fix the error in one and you do not realize you've forgotten others.

I've added some comments in 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 up to you.

    
17.02.2018 / 05:40