Retrieve content using Ajax request

Hey there, I've been tinkering with pure javascript to dynamically load content using AJAX without having to reload the entire page.

document.getElementById('dashboard').addEventListener('click', dashboard);

function dashboard(){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'dashboard.php', true);

  xhr.onload = function(){
    if(this.status == 200){
        history.pushState(null, null, '#dashboard.php');
      document.getElementById('content').innerHTML = this.responseText;
    } else if(this.status = 404){
      document.getElementById('content').innerHTML = 'Not Found';
    }
  }
  xhr.onerror = function(){
    console.log('Request Error...');
  }
  xhr.send();
}

Although this code functions as intended, there is a slight hiccup when manually refreshing the page - it reverts back to the original content. For instance, navigating to another page and then hitting refresh will display the Dashboard again.

I'm looking for a way to retain the current page even after a manual refresh. Any insights would be much appreciated. Thanks!

Answer №1

This piece of code functions flawlessly, big thanks!

<?php
if(isset($_GET['c'])){
    if($_GET['c'] == 'dashboard'){
        include('dashboard.php');
    }else if($_GET['c'] == 'form'){
        include('form.php');
    }
}else{
    include('dashboard.php');
}
?>

Answer №2

Within the realm of JavaScript and ajax, utilizing a PHP Session Variable proves to be the simplest and most commonly adopted approach. By incorporating this method while employing the get method, navigating through your platform becomes a seamless process. Once a PHP session variable is established, regardless of how frequently you refresh, the desired page is displayed either through concealment or redirection by validating the session variable's status. For further insights, please refer to this resource: PHP SESSIONS

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

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Sort by characteristics of embedded array - Knockout

I'm struggling with filtering a nested array using Knockout. My goal is to filter the array by both 'tag-names' and 'name'. For example, searching for 'whal' should display all objects that contain a tag with that name ...

What is the best way to retrieve the parameters from the current URL within an Express function on the backend? (details below)

Struggling to articulate my issue here. I'm in the process of creating a straightforward express app that utilizes the omdb API to search for movie titles and display the results. The challenge is that the omdb API returns the results in pages, with 1 ...

What's the best way to navigate across by simply pressing a button located nearby?

Hey there! I'm new to JavaScript and I'm working on a shopping list page for practice. In my code, I can add new items to the list, but what I really want is to be able to cross out an item when I click the "Done" button next to it, and then uncr ...

Is it possible to preserve the query parameters from the previous page using Vue Router's Navigation guard feature?

Hey there! So, I'm looking to pass a query from the current page to the next one without manually coding it into all of my push functions. I was wondering if there's a way to do this through Navigation guard or some hooks? I did some research an ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

"Enhance Your Website with Multiple Video Streams using YouTube API Events

Hello everyone! I am looking to include multiple videos on my website and have them start playing automatically when a user scrolls and the videos are in view. I want the speakers to be muted by default using the mute() function. Previously, I had succes ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

AngularJS: Issues with retrieving response headers following a $resource $save operation

When I run the $save function, which triggers my angularJS $resource to send a POST request to my API, everything seems to be working fine. I can successfully debug into the success callback handler and confirm that the object is created in my API. myObj. ...

There was an error in Three.js: "Uncaught ReferenceError: THREE is not defined"

Every time I try to execute my javascript code, I encounter the error message "Uncaught ReferenceError: THREE is not defined". The problematic line in my code is: var renderer = new THREE.WebGLRenderer(); // I have included the three.js library in the ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

Retrieve data from a collection by utilizing ng-repeat

I need help implementing a select interface on my website. Users will be able to choose a site, and then the associated country where the site is available will be displayed. To do this, I have a list of sites with information like their names and the co ...

Using JavaScript to dynamically load Cascading Style Sheets based on the current

I am trying to dynamically load different CSS files based on the current date (season). I attempted to tweak an image script that I found on Stack Overflow, but it didn't yield the desired result. Could someone please guide me on where I might be ma ...

Submitting Forms Across Domains in Internet Explorer

I have a lead form on my website that is connected to the Zoho CRM system. When I submit the form using Ajax, it works perfectly in all browsers except for Internet Explorer. Here is the code that I am currently using: $.ajax({ type: ...

Ways to utilize the this.context.router in ReactJS

Below is the code I have written: import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table' import sampleSystems from '../sample-systems'; class SystemTable extends React.Component ...

Issue with Jquery Mobile listview not showing up

I'm currently working on a PhoneGap application using jQuery Mobile, which consists of four main sections, each with its own HTML file. The issue arises when navigating from one section to another; for example, if I load the main.html page first and t ...

Executing JavaScript code within a class object using ASP-VB

I'm looking to create a function that will show a Javascript-based notification. I already have the code for the notification, but I'm trying to encapsulate it in a class library as a function. However, I am unsure about what to return from the f ...

Django: Implementing a database update feature with no need for redirection

After coming across a few examples, I'm curious about the most effective approach for achieving this: Is it possible to have a button on the template that can update something in the database when clicked, all without navigating away from or refreshi ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...

Error: `$(...).fullCalendar is not a function` when using React

After scouring through multiple posts discussing similar issues, I've noticed a common theme of problems arising from improperly loading jQuery or fullcalendar. However, in my case, I have both components loaded into my code (although I can't be ...