Retrieve the Current Time with an Ajax Request

Hi there, I am facing an issue with calling code from an ajax request for getting the current time. I have set up an HTML file with a working clock in it, but when loading the text from $container1, the clock and date are not displaying on the page. Can anyone help me understand why this is happening? The text from container 1 is loading fine, so why is the current time and date clock not functioning properly?

Here is the code snippet of what I currently have in the HTML file from which the data is being fetched:

// JavaScript code to display current date and time
var mydate = new Date();
var year = mydate.getYear();

// ... (remaining script as per original source)

// Displaying the date and time on the webpage
document.getElementById('time').innerHTML = Time + " " + dayarray[day] + " " + montharray[month] + "/" + daym + "/" + year + " " + hours + ":" + minutes + ":" + s + " " + ampm; 
document.getElementById('time2').innerHTML = Text + " " + dayarray[day]; 
}

// Loading content from container1 div
$('#container').load('C:/Program%20Files/TrueChem/Data/dashboard/src/Test.HTML #container1');

And here is the setup in the page where I want the content to be loaded:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">

// Function to refresh the page after a certain interval
function refreshPage() {
    // Code for refreshing the page
}
window.onload = function () {
    setTimeout(refreshPage, 3000);
    if (window.location.href.indexOf('page_y') != -1) {
        var match = window.location.href.split('?')[1].split("&")[0].split("=");
        document.getElementsByTagName("body")[0].scrollTop = match[1];
    }

    // Code for loading content from container1 div
{
    $('#container').load('C:/Program%20Files/TrueChem/Data/dashboard/src/Test.HTML #container1');
}
}
</script>

<div id="container">

Answer №1

It appears that there is an abundance of unnecessary code present in this section. My speculation regarding the issue at hand is as follows:

$('#container').load('C:/Program%20Files/TrueChem/Data/dashboard/src/Test.HTML #container1');

Your attempt to retrieve a file from the local file system using JavaScript seems to pose a significant security risk and will not function correctly. It's crucial to consider the potential security vulnerabilities if any website could access your local files.

When utilizing browser debugging tools, does it appear that an AJAX request is being initiated? Are errors being generated (hopefully)?

An AJAX request must be directed to an HTTP host, essentially a web server, in order to obtain the intended data. Loading local files using JavaScript is not permitted.

Edit: From the discussion below, it seems evident that you are endeavoring to execute certain JavaScript code on one page by loading it through AJAX from another page. This approach is unlikely to succeed because the requested page may lack the specific value sought; instead, it contains the code responsible for generating the desired value. Moreover, such code may not get executed when fetched via AJAX.

If your objective is to acquire the code rather than the page content, then the ideal solution would involve relocating the JavaScript code into a separate .js file and referencing it on both pages:

<script type="text/javascript" src="dateTimeCalculations.js"></script>

This method grants access to the code needed for value generation, enabling you to populate the value within elements on the page.

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

What is the process of incorporating a JS engine into an ASP.NET Core MVC React application?

An error will be displayed by the upcoming service. reference missing services.RegisterJsEngineSwitcher(settings => settings.DefaultEngineName = V8JsEngine.EngineName) .AddV8(); ...

Filtering in AngularJS can be performed by checking if a value in a specific key of one array is also present as a value in a specific

This query was originally posted on this thread I am looking to implement a filter that will display the values of colors.name only if they also exist in cars.color $scope.colors = [{"name":"blue","count":2}, {"name":"red","count":12}, ...

How can we effectively use mongoose populate in our codebase?

Hey there, I'm a newbie when it comes to nodejs and mongoose, and I could really use some assistance with mongoose populate. Can someone please help me understand this better? Thanks in Advance! Here are the schemas I'm working with: PropertySch ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

A guide on handling AJAX type posts using PHP

Here is a simple HTML form with an attached file input: <form enctype="multipart/form-data" class="Mesform"> <textarea maxlength="400" type="text" placeholder="Your message" class="MessageInp"></textarea> <div class="attach"&g ...

Receive alerts in Swift from WKWebView when a particular screen is displayed in HTML

Check out this sample HTML file I have. I'm currently using the WKWebView to display this HTML. My goal is to receive a notification in our Swift code when the user finishes the game and the "high score" screen appears, so we can dismiss the view and ...

What is the process for aligning a Component to the right within the Navbar in an AppLayout

In my project, the MainView class is an extension of an AppLayout. I am attempting to populate the Navbar with a logo on the left and the user ID on the right. Despite my efforts, both components keep aligning to the left side. Desired Navbar layout: ...

Encountering the error message "Unexpected token export" while attempting to implement the "framer-motion" package with Webpack

My experience with NextJS has been smooth sailing until now. I recently added the "framer-motion" module to animate some components, and it caused a major issue. Whenever I navigate to a page containing the import statement: import { motion } from "fr ...

Error: Unable to disconnect from the Twilio Video room due to an undefined reference to the room variable

Currently, I am utilizing the Twilio Video Javascript API for live streaming and recording video content directly from the browser. The application itself is developed using Node.js/Express, with the Twilio API being loaded from a CDN link on the page. As ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Error: Undefined property 'length' cannot be read by datatables

I am encountering an error while trying to implement datatables. The error message is as follows: jquery.dataTables.min.js:48 Uncaught TypeError: Cannot read property 'length' of undefined at jquery.dataTables.min.js:48 at i (jquery.dataTables.m ...

Setting up an OnMouseOver event for each URL on a webpage

Is there a way to add an OnMouseOver event for all anchor tags on a page, without replacing any existing event handlers that are already in place? I'm looking for guidance on how to achieve this using JavaScript or JQuery. Any suggestions would be gr ...

How to address text overlapping issue in IE11 with Flexbox

When viewed in Internet Explorer, you may notice that the content of the gray box is overflowing into the yellow box, a behavior not observed in other browsers. .parent { display: block; position: relative; border: 1px solid black; height: 300px ...

Encountering an issue while attempting to send a POST response through Node Express, specifically an error related

Encountering an error after completing registration, specifically when attempting to respond to the POST request. (user is added to database successfully) express deprecated res.send(status, body): Use res.status(status).send(body) instead auth\regi ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

The placeholder string is being accepted as the input value for the number

My issue is with a form input of type number. When the form is submitted without entering any number, it treats the placeholder text "rating" as the value. How can I stop this from happening? I need to make sure that the input number field is marked as in ...

How can I prevent the content on my page from adding padding to the body of the page?

I'm working on designing a simple interface similar to Slack. However, I'm facing an issue where the left navigation is creating some padding from the body, even though I have set the padding and margin to zero. .app { display: flex; flex- ...

Python Requests.get() fails to fully respond to XHR request due to an incomplete response

My current project involves scraping German zip codes (PLZ) based on a specific street in a particular city using Python's requests library. The data I am working with can be found on this server, and I'm applying techniques learned from here. T ...