Load TXT file - Refresh the contents - javascript

It's been a while since I tried my hand at HTML - and I'm getting stumped - hopefully someone can come to my aid.
My goal: On my LOGIN page, I want to add an "outage" notification section. I don't want the admins to access the login.html file; I want the data to be grabbed from a text file.
My attempt: I created an "outage.txt" file which is scheduled to update the webserver every morning. I then use a DIV and OBJ to load the "outage.txt" file. This does work.
<table><tr><td>
<div id="outage"><object width=475 data="outage.txt"></object></div>
</td></tr></table>
My problem: When I update my "outage.txt" file and refresh the page, the data is NOT reflected on the page. The only way I can get it to load correctly is to do a force-refresh (ctrl-F5).
What I tried:
-) I added meta data to not use cache. But it still does not update my data.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
-) I've changed my txt pull to JQUERY. It pulls the data nicely - but still does not update it.
$.get( "outage.txt", function( data ) {
Need help: At this point I'm not sure what to ask help for. Is there a better way to grab a text file and display it on the page? How to I ensure that the page is being correctly loaded and not pulled from cache. Is there a way to FORCE the page to force-refresh?

When I do a refresh (Ctl-R) on my Chrome, it updates the text.
Try:
window.onload = function() {
document.getElementById("objid").data = "outage.txt";
}
<object id="objid" width=475 data="outage.txt">

I have my answer and will do my best to summarize it here.
Looks like the browser sees the data="outage.txt" file and says 'Hey! I already have this in cache, no need to grab a file again'. The trick is to force a change to the filename which tells the browser that 'This is a new file, please load it no matter what'.
<div id="outage"><object id="outageid" width=475></object></div>
<script type="text/javascript">
document.getElementById("outageid").data = "outage.txt?" + Math.floor(Math.random() * 100);
</script>

Related

javascript error - Scripts are not found

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var path = '/Scripts/';
document.write('<base href="' + path + '"/>');
</script>
</head>
<body>
<h1>WELCOME</h1>
<script src="test.js"></script>
</body>
</html>
test.js
console.log("Message from external script");
output
error.png
Here you can see, first it try to load the script from body tag before it get the actual base href path from script section.
Is there any way to get come out from this error? I mean not to load body script until base href set.
Once the base href set, it executed successfully.
Thanks.
The behavior you're seeing is (somewhat) browser-specific, and is related to your use of document.write to set the base href dynamically.
Chrome and Firefox try to load the page resources before applying the document.write, then updates those urls and tries again after you set the page <base>. Safari appears to not do this; it uses the inserted base href immediately. I have not tested other browsers.
(In all browsers the <base> tag, whether static or dynamic, needs to appear in the document before any links that depend on it.)
Other than the extra network request this seems to be harmless (see below), but you could avoid it by using a static <base> tag instead of dynamically writing one in, or by setting the full path on the <script> tag instead of depending on the <base>.
(re "harmless": I checked the case where a test.js exists both at the root level and inside the "/Scripts" directory. Dynamically inserting the "/Scripts/" base href did not cause both scripts to execute in Chrome: successful network requests for both test.js files were made, but only the code in "/Scripts/" was executed. So the browser makers have handled that edge case already. Good job, browser makers!)
You Can use this code
<script src="./scripts/test.js" type="text/javascript"></script>

Website changes are caching and will not update for clients

I have made some changes on a live website (I know, not the best practice, but I was told to) and I'm having issues with caching. Every time I make a change to our CSS (SASS actually), I have to hit CTRL F5 to see the changes. That's not a problem for me, but the users are starting to complain of a broken website and many of them don't know how to clear the cache or use CTRL F5.
I have tried adding the following code, but it's not working.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
I have also tried adding this script:
<script type="text/javascript">
$(document).ready(function(){
$('img').each(function(){
var date = new Date;
// add the current unix timestamp in microseconds to the the image src as a query string
this.src = this.src + '?' + date.getTime();
});
});
</script>
I don't know Javascript though, so I don't know how to use it properly. I have searched for answers and other people have said these things work for them, but they simply are NOT working for me. I am a designer and front-end developer, so PHP and Javascript are a bit beyond me.
Finally, I've also read about using version tags - ?v=x.x, but my issue is the site was coded by other developers and I have no clue how they are linking to our stylesheet (using SASS).
Any help would be great appreciated!
Thanks!
Ideally you'd use PHP to check the file's filemtime() (the time it was last modified), and use a technique called versioning to indicate it's a changed file, and to not load it from cache.
The resulting HTML would look something similar to this:
<link href="/your/css/file.css?ver=<?php echo filemtime('/your/css/file.css'); ?>" rel="stylesheet" type="text/css"/>
Call the external CSS file adding a random code as GET variable in PHP.
Something like this:
<script src="yourfileUpdated.css?<?php echo rand() ?> rel="stylesheet" type="text/css" />
Styles are added with wp_enqueue_style function. Search your theme, it is probably in functions.php.
Then use like this:
wp_enqueue_style('main-styles', get_template_directory_uri() . '/css/style.css', array(), filemtime(get_template_directory() . '/css/style.css'), false);
Read more here https://wordimpress.com/wordpress-css-and-js-cache-busting/.

Embed markdown (md) into HTML

I need help embedding a markdown, or *.md, file inside of an HTML index file. I have found that I can embed HTML inside of markdown, but not vice-versa. This would help to increase the speed of my editing because markdown format is extremely easy to use, (as I'm using it now) and I don't have to change the format of the rest of my site. I know that something like this is done to embed another HTML file with <iframe src="path/to/html>html-name</iframe>. I could also use javascript to interpret the md format on page load. Thanks ahead of time.
Here's the solution that I have long since forgotten about:
Forgetting that I asked this question and getting no answers, I created my own solution as an extension off of Chris Jeffrey's marked.js.
I call it tagdown.js.
Here it is: http://spikespaz.com/tagdownjs/
Just in case that link, or my domain, expires: https://spikespaz.github.io/tagdownjs/
Github: https://github.com/spikespaz/tagdownjs
This allows markdown to be added directly to the site, within a tag set with the class markdown. See the example on the site. There is no theme system in it, it's just the markdown parser.
Update
The project, TagdownJS, has been deleted from Github. The code for it seems so simple that it doesn't deserve its own repository.
Until it finds a new home, just go find Christopher Jeffery's Marked.js, and use this following code with it.
document.body.style.display = "none"; // Hide the page until it's finished rendering.
document.createElement("markdown");
var md_tags = document.getElementsByTagName("markdown"); // Returns array of all markdown tags.
for (var i = 0; i < md_tags.length; i++) { // Iterate through all the tags, and generate the HTML.
var md_text = md_tags[i].textContent.replace(/^[^\S\n]+/mg, ""); // I love regex, so shoot me.
var md_div = document.createElement("div"); // Make a new div to replace the fake tag.
md_div.id = "content";
md_div.innerHTML = marked(md_text);
md_tags[i].parentNode.appendChild(md_div); // Add remove the old raw markdown.
md_tags[i].parentNode.removeChild(md_tags[i]);
}
document.body.style.display = ""; // Show the rendered page.
https://github.com/zhlicen/md.htm An example of zeromd.js Just serve the md.htm file and md files, and visit directly by url:
/md.htm?src=README.md
Live demo: https://b.0-0.plus/blog/md.htm?src=https://raw.githubusercontent.com/microsoft/vscode/main/README.md
Basicly, you need to interpret MD format into HTML. Javascript is an option.
Take below as an example. (Though Windows, independent of OS)
Let's say a folder mytest looks like,
D:\mytest>dir
Volume in drive D is Data
Volume Serial Number is ABCD-EFGH
Directory of D:\mytest
12/03/2020 10:10 AM <DIR> .
12/03/2020 10:10 AM <DIR> ..
12/03/2020 10:09 AM 7,973 example-image.jpg
12/03/2020 10:12 AM 4,619 md_html.html
12/03/2020 10:00 AM 2,299 md_html.min.js
3 File(s) 14,891 bytes
2 Dir(s) 778,204,147,712 bytes free
D:\mytest>
Here is the html content,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/atom-one-light.min.css" />
<link rel="stylesheet" href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" />
<title>Marked In HTML</title>
</head>
<body>
<template type="markdown">
Try Marked In HTML !
====
</template>
</body>
<script src="https://cdn.bootcss.com/marked/0.3.6/marked.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/languages/javascript.min.js" charset="utf-8"></script>
<script src="md_html.min.js" charset="utf-8"></script>
<script type="text/javascript">
markedInHtml.init()
</script>
</html>
And the js,
!function(n){function t(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return n[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var e={};t.m=n,t.c=e,t.i=function(n){return n},t.d=function(n,e,r){t.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:r})},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=1)}([function(n,t,e){"use strict";function r(n){return n&&n.__esModule?n:{default:n}}function i(n){if(Array.isArray(n)){for(var t=0,e=Array(n.length);t<n.length;t++)e[t]=n[t];return e}return Array.from(n)}function a(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.MarkedInHtml=void 0;var o=function(){function n(n,t){for(var e=0;e<t.length;e++){var r=t[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),u=e(3),l=r(u),s=e(2),c=r(s);t.MarkedInHtml=function(){function n(){a(this,n),l.default.setOptions(this.options||{gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,smartLists:!0,smartypants:!1,highlight:function(n,t,e){return c.default.highlightAuto(n).value}})}return o(n,[{key:"init",value:function(){var n=this;document.querySelectorAll('template[type="markdown"]').forEach(function(t){var e=document.createElement("div");e.innerHTML=n.parse(t),e.id=t.id,e.classList.add(["markdown-body"].concat(i(Array.from(t.classList)))),e.dataset.markdown=n.intelligentProcessingIndent(t),t.parentElement.replaceChild(e,t)})}},{key:"parse",value:function(n){return(0,l.default)(this.intelligentProcessingIndent(n))}},{key:"intelligentProcessingIndent",value:function(n){var t=n.innerHTML.split("\n");t.length&&/^\s*$/.test(t[0])&&t.shift(),t.length&&/^\s*$/.test(t[t.length-1])&&t.pop();var e=Math.min.apply(Math,i(t.map(function(n){return n.length?n.match(/^\s*/)[0].length:1/0})));return t.map(function(n){return n.substring(e)}).join("\n")}}]),n}()},function(n,t,e){"use strict";var r=e(0);window&&(window.markedInHtml=new r.MarkedInHtml)},function(n,t){n.exports=hljs},function(n,t){n.exports=marked}]);
And the jpg,
After open the html, you should be able to convert
Try Marked In HTML !
====
into
You can try to replace the template, some effect may not be able to present. For example, use quick markdown example by John Gabriele, the equation are not shown well.
Someone, like 🎅 would suggest to use snippet, yet I failed to get that ❄️ work, parsing not successful. 🥺

JQuery AJAX $.post failure to return data

I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps

how do i redirect to a welcome page from a html login form using javascript? The site is offline and on a development server

how do i redirect to a welcome page from an index page using javascript?
The site is offline and on a development machine and not in a server www directory like (wamp, lamp, apache etc) . I would like to do it without using PHP, python etc cause I already know how it is done in php using header(location ... ).
The directory structure
site
|
|--img
|--css
|--index.html
|--welcome.html
|--error.html
I have already tried window.location, window.location.href etc.
Inside the script of index.html.
if (true){
self.location("welcome.html");
}
else{
window.location.href = "error.html";
}
Though Window.location is a read-only Location object, you can also
assign a DOMString to it. This means that you can work with
window.location as if it were a string in most cases: window.location
= 'http://www.example.com' is a synonym of window.location.href = 'http://www.example.com'.
Mozilla Docs -- Window.location
It is not a function but you can assign a string to it.
Just write:
window.location="error.html";
self.location="error.html"; is fine too
You could also use a meta-refresh redirect:
<meta http-equiv="refresh" content="0;URL='welcome.html" />
Or just do window.location="welcome.html" instead of self.location("welcome.html")
``This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows:
<head>
<script type="text/javascript">
<!--
window.location="http://www.newlocation.com";
//-->
</script>
</head>
Thanks for all your advice.
But I was able to do it myself using window.location method. I found that the method was not the problem because I had tried it already previously.
The problem was that the redirection happened but since the function "checkLogin" was called by the onsubmit function of html element form,
it kept coming back to the same login page.
I fixed it by returning false at the end of the checkLogin() script.
But Thanks a ton for all your input.

Categories

Resources