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

Issue with Safari: Unable to trigger CSS :hover when tapping SVG element

On an iOS device in Safari, tapping this SVG element does not trigger the transition animation to fade in the replacement <g id="training-sub-menu">. The animation is confirmed to work, as there is a strange behavior where long-pressing whe ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...

Loading jquery dialog content using ajax

I have run into an issue while trying to load a form into a jQuery dialog via AJAX. When checking in Firebug, I noticed that the request URL contains a strange parameter like "_=1283928792723", which is causing the request to fail with a 406 Not Acceptable ...

SQL command for fetching additional data

Whenever I click on the load more button, it is supposed to load comments for a specific post from the database using the post_id. However, the issue arises when I click load more as it ends up loading all the comments from the database table. pagecomment ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Sort the y-axis based on the earliest date

The ticks I am using are as follows: ticks: 0: [3, Tender Period, 2014-03-11] 1: [1, Pre-Contract Preparation, 2014-03-17] 2: [2, Contract Period, 2014-06-10] However, on my chart, it starts with [3, Tender Period], so why is my second object ...

Dynamic Code for Removing List Items Based on Date

I need assistance in resolving an issue with my company's website design and function. Specifically, I am working on a page that displays a list of events where employees will be present throughout the year. Here is an example: <div class="contai ...

Creating a seamless user experience using jQuery and Ruby on Rails through the combination of AJAX functionality and ensuring

I am in search of a method to effectively call a custom function from the submitHandler for proper ajax post. Here is the custom function I have created: jQuery.fn.submitWithAjax = function() { this.submit(function() { $.post(this.action, $(this).seriali ...

PHP and mysqli combine to create a versatile image slider with changing images

I am looking to implement an image slider that can be updated by the admin using php and mysqli. The admin should have the ability to easily add or remove images as needed. ...

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Hide a header and bring it back after a 2-second delay

I REPLIED BELOW Is there a way to make the header of my webpage fade out when scrolled and then be hidden using style.display? Here's what I have so far: <script type="text/javascript> function Scroll() { var head = document.getEl ...

What is the best way to add an Apple iPhone-like effect to a menu list?

I've been working on creating a menu similar to the Apple menu using the greensock api Here is my progress so far: JSFIDDLE Update This is what I am aiming for: Fiddle Any idea why there is flickering when hovering over it? <div class="de ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

Retrieving an array from a JQuery For Each Loop

I'm struggling to retrieve an array of basic information from a for each loop, but so far I haven't been successful. Below is the code snippet I am utilizing within two separate functions. function getUser(uname, callback) { var u = "http://itsu ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Is the Wordpress search bar a clickable link?

Whenever I attempt to click on the search box, it redirects me to the comments section of a post as if it were a link. It's difficult to provide more information about this issue, but the problem occurs on the website lbk.newcoastmedia.com/wordpress w ...