DEV Community

Cover image for Move from one page to another without loading
Clément Gaudinière
Clément Gaudinière

Posted on

Move from one page to another without loading

Hello everyone, today we meet in a new tutorial. We are going to see how to go from one page to another without loading the page. You have probably noticed it if you are attentive, on some websites, when you go from one page to another there is no loading. There are different techniques more or less heavy to do this, we can for example use the PHP Symfony framework but you have to organize your files in a precise architecture, it is therefore more complicated to implement when the website already exists. That's why today we use AJAX, and to make it faster, jQuery.
Important note : all files will be in PHP, make sure you can run them.

The basics

To begin with, I propose the following architecture for our files :

Architecture for our files

You don't have to follow it, but you will have to be careful and rigorous about the location of the files.
Our site will be called www.site.com in this example, you will have to replace this name with your domain name, the IP of your site or the location of your PHP file on your computer if you use a local web server. The index.php file will contain our home page, while the login.php page will contain a connection form. The src folder contains several other folders, the one we are interested in here is php, which contains the start and end of each web page. You will understand later why it is important to create these two files.

index.php

Our index page is quite simple, it contains a php title variable, the file early.php if we want it to be whole and not just ask for the content. The content of the index page is : a title and a paragraph. Finally, it contains the end file end.php if we want it to be whole and we don't just ask for the content. Otherwise we change the name of the page with a script. So our index page looks like this :

<?php
  $title = "Index page title";
  if(!isset($_GET['section'])){
    include 'src/php/early.php';
  }
 ?>

<h1>I'm the title</h1>

<p>Morbi tincidunt congue diam, at vestibulum elit tempor a. 
Donec id mi malesuada, auctor ligula in, aliquam metus. 
Vestibulum in faucibus massa. Nullam luctus et diam et posuere. 
Nulla massa metus, mattis et efficitur eu, vehicula in lectus. 
Sed a sapien quis tellus rhoncus efficitur. 
Integer sed ultrices nisl, vitae aliquam tellus.</p>


<?php
  if(!isset($_GET['section'])){
    include 'src/php/end.php';
  } else {
    ?>
    <script type="text/javascript">
      document.title = "<?= $title ?>";
    </script>
    <?php
  }
?>
Enter fullscreen mode Exit fullscreen mode

login.php

The login.php page, contains basically the same thing except that the title is not the same and the content is different :

<?php
  $title = "Login page title";
  if(!isset($_GET['section'])){
    include 'src/php/early.php';
  }
 ?>

<h1>Login</h1>

<form action="" method="post">
  <!-- Form to be completed later (optional) -->
</form>

<?php
  if(!isset($_GET['section'])){
    include 'src/php/end.php';
  } else {
    ?>
    <script type="text/javascript">
      document.title = "<?= $title ?>";
    </script>
    <?php
  }
?>
Enter fullscreen mode Exit fullscreen mode

early.php

As you may have realised before, the early.php page is the start of our other two pages: index.php and login.php. This file should be started as a well presented HTML document. We need to include jQuery, you can include it via a CDN or directly host it on your server or computer. Finally, you can add a header. The file ends with the beginning of the div with the id main-content which will contain the content of our pages afterwards :

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">

    <!-- A style file that can be created after  -->
    <link rel="stylesheet" href="src/style/css/style.css" />

    <!-- We include jQuery with the Google CDN  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <meta name="viewport" content= "width=device-width, initial-scale=1.0">
    <title><?= $title ?></title>
  </head>
  <body>
    <header>
      <div>
        <a href="index.php" class="crayons-btn crayons-btn-main">index</a>
        <a href="login.php" class="crayons-btn crayons-btn-scd">Login</a>
      </div>
    </header>
    <div id="main-content">
Enter fullscreen mode Exit fullscreen mode

end.php

This file will contain the end of our pages, so it will be necessary to close some tags like the main div, or the body or the html tags. We will include the AJAX part :

    </div>
  </body>
  <script type="text/javascript">
  $("a").click(function(e){
    e.preventDefault();
    $.ajax({
       url : $(this).attr('href')+"?section=true",
       type : 'GET',
       dataType : 'html',
       success : function(code_html, statut){
          $('#main-content').html(code_html);
       }
    });
    window.history.pushState("","", $(this).attr('href'));
  });
  </script>
</html>
Enter fullscreen mode Exit fullscreen mode

Let's unpack this AJAX code which can be complex if you don't know how AJAX requests work. First of all the first line of the script detects the event: "When someone clicks on a link". If this is the case, it launches the function. The second line tells the browser not to load the link if it is compatible with AJAX requests. Then we make our AJAX request by specifying the url and passing as a parameter section=true, so the page will not load completely. We then specify the type of request here GET. If successful, we update the content of the "main-content" div with the new content. Finally, we modify the url of the page.

Add some style

You can then create a file to add some style. This will be placed in the src then style then css file, and will be called style.css. For my part, my file looks like this :

#main-content{
    width: 1000px;
    max-width: 95%;
    display: block;
    margin: auto;
    font-family: cursive;
}

#main-content h1{
    text-align: center;
}

body{
    margin: 80px 0 0 0;
}

header{
    background: whitesmoke;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
header div{
    width: 1000px;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: flex-end;
    align-items: center;
    margin: 13px auto;
}
.crayons-btn{
    margin: 0 5px;
    padding: 0.5rem 1rem;
    font-size: 1rem;
    position: relative;
    display: inline-block;
    border-radius: 5px;
    outline: none;
    user-select: none;
    font-family: inherit;
    line-height: 1.5rem;
    font-weight: 500;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    white-space: nowrap;
    transition: all cubic-bezier(0.17, 0.67, 0.5, 0.71) 100ms;
    border: 0px solid;
    overflow-wrap: normal;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
.crayons-btn-main{
    background-color: blue;
    border-color: transparent;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    color: #f9fafa;
}
.crayons-btn-main:hover{
    background-color: #6b6bf1;
}
.crayons-btn-scd{
    background-color: #f1f1f1;
    border-color: transparent;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    color: #363d44;
}
.crayons-btn-scd:hover{
    background-color: #dddddd;
}
Enter fullscreen mode Exit fullscreen mode

The result

Below you can see the final result, when you click on one of the two buttons: index or login, the page only loads the main-content part, the rest does not move.

Overview of the result

I hope you enjoyed this tutorial, if you have any questions, feel free to ask me in the comments. 👍

Latest comments (2)

Collapse
 
roneo profile image
Roneo.org

?

Collapse
 
clementgaudiniere profile image
Clément Gaudinière

I had published it without finishing it 🤣