Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear.

Here is the structure of a website:

  • Mainpage (Containing all resources and scripts)
    • All Other pages (HTML only consists of elements of that specific page)

When a user clicks on mainpage anchors leading to other pages, an AJAX function embedded in the On click event will run, and the URL address will change using Window.history.PushState.

The problem arises when a user enters the URL of other pages directly instead of clicking on anchors. For instance, if a user enters: http://example.com/pages/about, only the elements of that page will load without the necessary resources and scripts from the mainpage.

I am thinking of a solution like this:

  1. Detect whether a user enters the URL instead of clicking on anchors (detect HTTP request).
  2. If it is an HTTP request, then load the resources included in the mainpage.

Is there a way to implement this solution using client-side (javascript) or maybe PHP?

You can refer to Cloudflare panel to understand what I mean:

Answer №1

After conducting some research (with a special thanks to the comments), I have come up with my preferred solution. I made the decision not to alter the markup, therefore opting out of using Template engines.

1. Begin by creating this PHP Script and saving it in a PHP file.

<?php

/* Check for AJAX */

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    /* Code to execute if it is an AJAX request */
}

else {
/* Code to execute if it is not an AJAX request; In my case, I echoed all scripts and resources that needed to be in AJAX addresses */
    echo '
        <script src="example.js"></script>
    ';
}

2. Include the above PHP script file in pages where both AJAX and HTTP requests are present. In my scenario, I included it in all other pages except the main page.

<?php include "../script.php"; ?>

3. Configure your webserver to support PHP scripts within HTML file extensions. As my webserver was Apache, I added the following line to the .htaccess file.

AddType application/x-httpd-php .htm .html

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

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

Can we rely on JavaScript to maintain the order of object properties?

Let's say I define an object in the following way: var obj = {}; obj.prop1 = "Foo"; obj.prop2 = "Bar"; Is it guaranteed that the object will always appear exactly like this? { prop1 : "Foo", prop2 : "Bar" } In other words, will the properties reta ...

Is it possible to utilize Jquery in order to add an opening <tr> tag and a closing </tr> tag within a dynamic table?

I have been experimenting with the code snippet below in an attempt to dynamically add a closing tag followed by an opening tag after every three cells, essentially creating a new row. Progress has been made as the DOM inspector shows a TR node; h ...

REACT Issue: Unable to Select Dropdown Option with OnChange Function

I have a component that includes a select element. Upon clicking an option, the OnProductChange function returns the value. However, my e.target.value shows as [Object Object]. Yet, {console.log(product)} displays: {id: 1, name: "VAM"} Clicking on Add L ...

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

The rows sent to HTML/Bootstrap from Java through JSON do not neatly wrap across rows evenly

I am having trouble getting images to wrap evenly on an HTML/Bootstrap page that are retrieved by Java and passed through JSON. Despite my expectations, there is a third row created with only one image and a fifth row with 3 extra images. Additionally, whe ...

The Vue/Nuxt application displays content duplication on each page, rendering the content twice without duplicating the components

I recently delved into Vue/Nuxt programming and worked through a tutorial on adding a blog, which I then customized for my website. Everything functions perfectly except that the content is rendering twice. It goes from rendering NavPage (component) > cont ...

Contrasting assign and modify operations on arrays

After spending 2 days searching for a bug in my angular2 project's service.ts file, I finally found it and fixed it. However, I'm still trying to understand why the working code behaves differently from the bugged one, as they appear identical to ...

Showing the inner text of a jQuery knob in two separate lines

Can the number displayed within the knob be shown with additional text on a new line? I know about the 'format' hook that can append text to the number, but I would like to include a line break as well. ...

Panel not refreshing its content after update

I've been working on this for a while, but I'm still stuck. Here's the code from the aspx page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns= ...

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Having difficulty removing an element from JSON using PHP

I am encountering an issue with deleting elements from JSON based on key value using PHP. I have provided the code snippet below: <?php $comment = json_encode(array(array('day_id' => '', 'comment' => ''),ar ...

If the text is too lengthy, enclose it within a div element

I am facing an issue with a fixed width DIV of 300px. Within this DIV, I have dynamic text that sometimes exceeds the width and gets cut off. Is there a way to make the text wrap when it exceeds the 300px limit without increasing the height of the DIV? Is ...

Navigating through nested arrays in Laravel Blade templates

I have an array that is displaying the code below after being dumped. array:1[ "123"=>array:3[ "test1" => 12345 "test2" => "test" "test3" => 123 ] ] When trying to display each element in an HTML table, the val ...

Retrieve the current user's local machine name on a wireless network using PHP

Attempting to obtain the user's machine name using: gethostbyaddr($_SERVER['REMOTE_ADDR']); However, only receiving the host name which is identical for all users in my wireless network. After conducting research online, some suggest it ...

What is the process for acquiring dynamic values within a URL?

My website's current URL is www.xyz.com/folder-name/filename.php I'm looking to change it to: www.xyz.com/dynamic-value-1/dynamic-value-2/listen(this part stays the same)/? Thanks! ...

Employ fwrite function to generate a Markdown file

Is there a way to utilize the fwrite() function to generate an .md file? I am in the process of developing a blog for a team that requires the ability to upload content without manual typing. The content is structured in markdown format within an .md file ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...