What is the best way to navigate between elements using AJAX?

My experience in Ajax is minimal. I've managed to create two <li> elements with <a> elements inside, each linking to different HTML files. My goal is for clicking on a link to automatically load the corresponding HTML file without refreshing the page, but it's not functioning as expected. When I click on a link, nothing occurs. Appreciate any assistance! Using jQuery with Ajax.

FIRST HTML FILE

$('li').find('a').on('click',function(event) {
    event.preventDefault();

    var href = $(this).attr('href');

    $('.main-content').load(href + 'content-ajax');
});
  
.ajax-img {
    margin-top: 8em;
    float: left;
}

.ajax-img2 {
    float: left;
    margin-left: 10em;
    margin-top: -5em;
}

.ajax-nadpis {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 800px;
    font-size: 2.7em;
}

.ajax-text {
    display: flex;
    justify-content: center;
    align-items: center;
    
    font-size: 1.5em;
    margin-top: -13em;
}

nav {
    display: flex;
    
}

ul li {
    display: inline-block;
    padding-left: 18em;
    margin-top: 2em;
    
}

ul li:hover {
    cursor: pointer;
    text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>

//FIRST HTML PAGE

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Responsive Website</title>
    <link rel="stylesheet" href="css/styles2.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Cinzel&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Tinos&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet">
</head>
<body>
 
    <h2 class="podnadpis">Automatic loading articles using ajax (without page refresh)</h2>
    <section class="ajax">
        <div class="section-container">
            <div class="img-holder">
                <img src="ajax-IMGs/talltales.png" class="tall-tales-logo" alt="logo tall tales">
            </div>
        </div>
        
    </section>
    
    <article id="article">
        <nav class="navigation">
            <ul>
                <li><a href="ajax1.html">Shroudbreaker</a></li>
                <li><a href="javascript.html">Skeleton Lords</a></li>
            </ul>
        </nav>
        <div class="main-content">
        <div class="content-ajax">
            <img src="ajax-imgs/graymarrow.png" class="ajax-img" alt="">
                <h3 class="ajax-nadpis">SKELETON LORDS</h3>
                <p class="ajax-text">Tall Tales – Shores of Gold introduces Skeleton Lords, imposing characters clambering out of the oldest legends into the present day. Meaner than any of the bony marauders you’ve fought so far, these intimidating adversaries can only be encountered by following the story as it unfolds. Be prepared for anything when seeking out Skeleton Lords – these resourceful foes will resist any attempt to send them back to their resting place beneath the sands. They’re big, tough and full of surprises…</p>
            </div>
        </div>
    </article>

    <script src="javascript/jquery.js"></script>
    <script src="javascript/jquery.parallax.js"></script>
    <script src="javascript/main.js"></script>
</body>
</html>

SECOND HTML FILE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Responsive Website</title>
    <link rel="stylesheet" href="css/styles2.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Cinzel&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Tinos&&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet">
</head>
<body>
    
    
    <article id="article">
        <nav class="navigation">
            <ul>
                <li><a href="ajax1.html">Shroudbreaker</a></li>
                <li><a href="javascript.html">Skeleton Lords</a></li>
            </ul>
        </nav>
        <div class="main-content">
        <div class="content-ajax">
        <img src="ajax-imgs/shroudbreaker.png" class="ajax-img2" width=700px height=600px  alt="">
            <h3 class="ajax-nadpis">SHROUDBREAKER</h3>
            <p class="ajax-text">The Shroudbreaker is the first Tall Tale in the Shores of Gold Arc. The Tale Book can be voted for on the table next to the Mysterious Stranger in the Tavern of any Outpost. The Tall Tale can be voted to be cancelled at the Ship's Voyage Table. Players can unlock three Checkpoints during this Tall Tale. If they wish to continue the Tall Tale at a later time, they can vote on any acquired Checkpoints at the Voyage Table.</p>
        </div>
        </div>
    </article>

    <script src="javascript/jquery.js"></script>
    <script src="javascript/jquery.parallax.js"></script>
    <script src="javascript/main.js"></script>
</body>
</html>

The issues I'm encountering are shown in this image: https://i.stack.imgur.com/0VgsT.png

Answer №1

Implementing AJAX to Load Page Content

To streamline the process of updating elements like headers and footers across multiple files, consider utilizing a templating engine such as PHP. This allows for easy modification in one central location rather than editing numerous individual files.

For seamless navigation without page refreshes, Ajax plays a crucial role:

header.php:

<!DOCTYPE html>
<html>

<head>
    <meta charset=utf-8 />
    <title><?= $page_title ?></title>
    <link rel="shortcut icon" href="#!" type="image/x-icon">
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <nav id="nav">
        <a href="index.php">Home</a>
        <a href="about.php">About</a>
        <a href="contact.php">Contact</a>
    </nav>

and footer.php:

    <footer>
        &copy; <?= date("Y") ?> - Lorem Ipsum
    <footer>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>

</body>
</html>

Create individual files index.php, about.php, and contact.php following this structure with unique content under each <h1> tag.

<?php
$page_title = "Home";
include 'header.php';
?>

<div id="page">
    <div id="content">
        <h1>This is Home page</h1>
    </div>
</div>

<?php
include "footer.php";
?>
<?php
$page_title = "About";
include 'header.php';
?>

<div id="page"gt;
    <div id="content"$gt;
        <h1>This is About page</h1>
    </div>
</div>

<?php
include "footer.php";
?>
<?php
$page_title = "Contact";
include 'header.php';
?>

<div id="page">
    <div id="content">
        <h1>This is Contact page</h1>
    </div>
</div>

<?php
include "footer.php";
?>

Here's the JS code from script.js:

jQuery(function ($) {
    // Handle history states
    window.onpopstate = function (e) {
        if (e.state) {
            $("#content").html(e.state.html);
            document.title = e.state.pageTitle;
        }
    };

    $("#nav").on("click", "a", function (ev) {
        ev.preventDefault(); 

        const URL = $(this).attr("href"); 
        const name = $(this).text(); 
        document.title = name;

        // AJAX LOAD and pushState for browser history
        $("#page").load(URL + " #content", function (data) {
            const html = $(data).find("#content").html();
            const pageTitle = $(data).find("h1").text();
           
            window.history.pushState({html, pageTitle}, "", URL);
        });
    });
});

Ensure that you have PHP installed and configured in your Environment Variables. Launch a PHP cli-server by running the command below in your project directory:

php -S localhost:8080

Navigate to http://localhost:8080 in your browser to view the implementation. This approach is search-engine optimized, enabling crawlers to index all pages efficiently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using CSS and Bootstrap together in the Yii2 framework

Hey there, I'm new to Yii2 and recently put together a layout page. However, I seem to be having some trouble with my CSS - it's not fully loading, only parts of it are displaying correctly. Is there anyone out there who can lend a hand? This is ...

the prepared statement resulting in an error within the while loop

In my simple mysqli PHP application, I encountered an issue where the while loop in my code never gets entered even though the query seems valid and produces results when executed directly in MySQL. After adding output statements for debugging, I found tha ...

I'm having trouble finding a solution to remove the white space

I've been troubleshooting a website and noticed some unexpected whitespace on the page. Even though I have set my page wrapper div and other elements to width: 100%, the content in between is not utilizing the full width of the screen. I suspect this ...

What is the best way to obtain a reference to the parent form element within an AngularJS directive?

Here is the HTML code I am working with: <form name="my-form"> <div class="col-sm-4"> <input type="phone" name="mobileNumber" ng-model="form.mobileNumber" value="0439888999" required> </div> </form> In addition, I ha ...

What is the best way to customize the small square area found between the vertical and horizontal scrollbars?

Please take a look at the images provided below: https://i.stack.imgur.com/QVHfh.jpghttps://i.stack.imgur.com/cubd8.jpg Whenever both vertical and horizontal scrollbars intersect, it results in a square space. This phenomenon occurs not just within the b ...

Tips for scrolling a div that has too much content within a webpage

Is there a method to manipulate the scrollbar within a div on a webpage? Specifically, I am attempting to automate scrolling up and down on an Instagram post like . However, since the scrollbar may be hidden using CSS properties, detecting it can be challe ...

When the state inspection fails due to a missing object property, the function will not work as intended

I'm currently in the process of developing a weather app. The user will input either a zip code or a city name + state, triggering the $.getJSON function to gather data. One key feature I am working on involves checking if the user's input is va ...

When Flash components are hidden and then shown again, they monopolize the mouse wheel scrolling function, causing issues in

Hi all, I'm in need of some insights. I've been looking into the well-known issue of 'Flash hogging keyboard focus', but I believe our specific problem might require a workaround that someone else has already discovered. Despite trying ...

Policy regarding copyright content removal and protection of privacy

In the majority of musical websites I have come across, they often mention the following in their policies: At this particular website (www.Indiamp3.com), you will find links that redirect to audio files. These files are hosted elsewhere on the internet a ...

To Ajax or not to Ajax, that is the question

I am currently faced with a decision while creating a quiz web application - should I opt for ajax or complete postback to evaluate the user's answers? In this system, users enter their answers in a textbox and hit the submit button for each question ...

Is it possible to create a CSS code that targets specific browsers for a particular style to be applied?

My project has external CSS that contains all the styles for my site. The site looks great in Firefox, but it becomes a mess in Internet Explorer (as usual). Is there a way to write CSS so that specific styles only apply to certain browsers? For example, ...

VueJS does not support loading Jquery

When setting up my project with Bootstrap, I encountered an issue where even though I imported the jquery.min file before Bootstrap in my main.js file using require(), Bootstrap still threw an error saying that it requires jQuery. In my main.js file, I ha ...

Creating a secure API design to restrict public access when integrated with AJAX functionalities

In the process of developing an API for my app, I am aiming to enable external domains to make queries using a POST request. This is expected to be primarily done through client-side protocols like AJAX. One of the key considerations in designing this API ...

Are there ways to implement Vue.js transitions without directly setting the height in the code?

I'm having an issue with a Vue app I created where I need to make an element expand and collapse when a button is clicked. I want the effect to be smooth and animated, but using the <transition> tag alone isn't working as expected. The prob ...

Tips for creating a stylish scrollbar in a React Material-Table interface

Currently, I am utilizing the react material-table and looking to implement a more visually appealing scroll-bar instead of the default Pagination option. Although I have experimented with the react-custom-scroll package, it has not produced the desired ...

The issue with Grid component in Nested Single file Component

I'm currently working on creating a grid component in Vue to set up a sortable and searchable chart using Single File Component. I've also integrated vue-router into the project. Below are my two .vue files. At the moment, I can only see the sear ...

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Arranging elements in columns using Bootstrap

I am facing an issue with my columns in bootstrap, as they are currently appearing vertically, one above the other. I need them to be displayed side by side Here is the code I am using: <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12 col-12 layo ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...