I am trying to include many HTML files into a specific DIV - javascript

I create HTML files of press articles as separate entities as they can appear in several places in the website. In one place I want the ability to display all articles for a particular year into a specific div Called "news".
I found the w3 schools include html code this is fine except it always displays the included HTML as a new window. I have tried several methods but no luck. Do you know what coding changes i would need to do in order to achieve my aim. I think I need a (Document.getelement by id) but cannot work out where to put the code.
enter code here
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
<html>
<!-- Content.html -->
Google Maps<br>
Animated Buttons<br>
Modal Boxes<br>
Animations<br>
Progress Bars<br>
Hover Dropdowns<br>
Click Dropdowns<br>
Responsive Tables<br>
</html>

I would advise against the JavaScript approach; and simply opt to render your cumulative pages at the server end, and then serve out the built-up HTML. Here's the elementary how-to.
The simplest thing to do would be to have a plain text file with all the articles for a given month listed. Suppose we put the following into indexes/Press2019.txt, one entry per line:
Apr20.html
Mar20.html
oct19.html
sept19.html
July19.html
...
Then, suppose we have a simple PHP file, press.php, as follows (please read the inline comments to understand what the code is doing):
<!DOCTYPE html>
<html lang="en">
<?php
// Validate the "year" request as a valid integer
$year = isset($_GET['year']) ? filter_var($_GET['year'], FILTER_VALIDATE_INT) : false;
empty($year) && die('Invalid Year!');
// Check if an index for the year exists
$path_index = "indexes/Press{$year}.txt";
!is_file($path_index) && die("No press index for year {$year}!");
// Load list of articles
$texts = file($path_index, FILE_IGNORE_NEW_LINES);
// Function for HTML title & header
function make_header($title) {
echo "<head><title>{$title}</title></head>";
echo "<body><h1>{$title}</h1>";
}
// Output header
make_header("All Press Articles for Year {$year}");
// Output all articles
foreach($texts as $file) {
$path = '/html/press/' . $file;
$html = file_get_contents($path);
$html = parse_body($html); // read below for explanation
echo $html;
?>
</body>
</html>
This would load and output all the articles in your list into one page.
I'm assuming that your individual articles are also static HTML files with <html>, <body> etc. tags included. If not, you can remove the parse_body function above. If yes, we need to clean them up. (This would also be an issue with the JavaScript approach you experimented with in the OP.)
We can accomplish this with a simple regular expression function included in the press.php file:
function parse_body($html) {
if (preg_match('#<body>(.+)</body>#is', $html, $match)) {
return trim($match[1]);
}
return 'No content matched!';
}
Then, all you'd need to do is make a link like press.php?year=2019, and have plain text page index files in the indexes folder. You could double up your index files to generate the HTML you posted in your comment to the OP, suppose a file called monthly.php, with the second half of the code above replaced with:
// Output header
make_header("Links to Monthly Press Articles for Year {$year}");
// Output links to monthly pages
foreach($texts as $file) {
echo "{$file}";
}
That would give you monthly summaries with links: Simply link to monthly.php?year=2019 (or whichever year) to get a year's links summary. Less manual HTML coding = less errors, easier updating, and more time saved for actual productive work. :)
Now, there are fancier ways of doing this. This would be the first step in leveling up from manual HTML writing. With a bit of experimentation and a couple of basic PHP tutorials, you could easily customize this and adapt it to different contexts.
This isn't an answer to tweaking the JavaScript in the OP to do the job; but it is a fairly simple solution to the actual question, "I am trying to include many HTML files into a specific DIV". This answer turned out to be "code writing service", which SO by definition is not. But you're on with a good cause, so. Best of luck, hope this helps.

Related

Searching for keywords in a document by looping through an array

I am working on a script to read and search for keywords in a text file that is uploaded to a website. I have an idea about how to read a string and report the number of occurrences of a word using RegEx, but I can't figure out how to access the text from fileReader once it is loaded. I want to call this script by clicking on the "Start Coding" button after the FileReader has done its work. I created a function to make this work, but I can't figure out how to access the file reader text. Thanks for your help!
I got the script for the fileReader from here How to read text file in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<button onclick="myFunction()">Start Coding</button>
<script type="text/javascript">
alert ("Please insert your text in the box below and we will begin searching")
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
function myFunction() {
alert("We will start by highlighting all the required search terms then we will being our search by looking for the instances of the word 'pilot'")
var count = (txt.match(/program/g) || []).length
alert ("your word occured " + count + " times.")
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
Update
I figured out how to connect to the documents that were loaded onto the site thanks to NinjaM and some more research. I had to connect to the ID and used the .innerHTML method to connect with the uploaded document. Everything is working fine, except I now have a new problem with getting my loop to work properly.
I want to have users upload a document to this site and then have them click through a series of buttons that search for keywords in the document. I work with an organization that is coding documents on climate change and I'm trying to speed up the process. Typically, a person reads through the documents and then uses control-f to search for certain climate change keywords. If the keywords are in the document in the right context, then the user makes a note of it in our database. This site will automate that process and reduce some of the risk that people will not search for the appropriate term or won't search all of the terms.
I have a series of RegEx expressions that I would like to put through a loop and search for in the document. I made the loop and the expressions but I would like for my loop to start over again after it has search through each item in the array. For example, once it has searched the document for the key word pilot I would then like for it to start at the beginning again and search the whole document for the keyword project. Right now the search looks for pilot in the document and then once it finds the last instance of pilot, it moves on to project. This is the portion of the code that I would like help to fix :
function windowFind(){
var pilotWords = ["pilot","project"];
for (var i = 0; i < pilotWords.length; i++) {
("Find -> are = " + window.find(pilotWords[i]))}
}
You can check out a basic version of the site on github https://calebdow.github.io/ You will have to find upload a test file
The contents of the text file would be displayed in
<div id="main">
...
</div>
or in plain text when you run the open the html file. As far as using the text in Javascript, it would be place in a variable named output which is defined in the code.

loaded js works different to hardcoded

I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…
The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)

Can't populate <div> with elements of a json_encoded php array

This function worked previously (the last time I opened this project over a week ago), but now I can't seem to get it to work at all and I have no idea how to figure out what's going wrong! First, I'll diagram my file architecture in case my file paths are incorrect and causing my php to not even be called:
~/Sites
proj1
htdocs
index.html
ajax.php
scripts
java_script.js
styles
style_sheet.css
includes
scrapedImages
.
.
.
Here's the JS function that uses AJAX to call a .php script:
function requestServer() {
$.getJSON('/Users/aweeeezy/Sites/proj1/htdocs/ajax.php', function(data) {
$.each(data, function(key, val) {
var html = "<img src='/Users/aweeeezy/Sites/proj1/includes/scrapedImages/"+val+"' style='display:block;max-width:20px;max-height:20px;width:auto;height:auto' alt=null />"
$('#puppy-box').prepend(html);
});
});
}
The line setting var html was <img src='...'+images[i]+"... when I first opened the project this morning, but I'm not sure why...I think because I was testing the site out, it was faster to only load a fraction of the images and used a for loop to cycle through only the first 10 or so pictures, hence the i index. Anyway, shouldn't it be data[i], or val[i]...or data[val]? I have no idea what's going on here.
Here's the ajax.php file that the JS function is trying to call:
<?php
$images = scandir('/Users/aweeeezy/Sites/proj1/includes/scrapedImages/');
/*foreach ($images as $key => $image) {
if ($image == '.' || $image == '..') {
unset($images[$key]);
}
}*/
echo json_encode($images);
?>
I commented out the middle part because I wasn't sure if this was causing a complication. I tried putting both echo and print lines in here to see if the script is being called, but even if they are working, I can't really see them because they're being returned as data (I think) to the JS function that calls the script.
How do I even go about debugging this mess and get my girlfriend's valentine's day project back on track!

PHP var->Javascript->PHP

I'm working on a project that has the following problem:
The database gives(via php) an array with a list of JavaScript files that need to be loaded. it is stored in the variable $array(php). I need to extract those source files with php(foreach loop) and load them via JavaScript. It is like this:
document.write("<?php foreach($js_files as $filename) {if( trim($filename) <> "" ){echo '<script type=\'text/javascript\' src=$filename></script> \n';}} ?> ");
The problem is that it loads a couple of files but goes wrong with the first one(a google api file). Does anyone have a sollution to this? Or any ideas in which direction i have to look.
This is a bad idea on multiple levels, but can be fairly easily resolved. But first:
1) Never use document.write(). To dynamically load a script it is better to use:
var script = document.createElement('script'); //create a script element
script.src = 'javascript.js'; //path to src file
//now get the body element and append the new script element
document.getElementsByTagName('body')[0].appendChild(script);
2) Loading scripts like this will likely not work if they need to be loaded in a particular order, as the downloading of dynamic scripts occurs asynchronously (non-deterministic)
3) Generally speaking, you should concatenate your js files to reduce http requests, you can use a tool like grunt to make an automatic build process.
4) If you really, really want those scripts to be dynamically loaded though, you can use the process I outlined in (1) to get the file names use ajax:
//depends on jQuery, but could be written vanilla if needed
$.get('myPhp.php', function(resp){
var arr = resp.split(','); //splits returned string on the comma
var i = arr.length;
//iterate through the results set
while (i--) {
//do process from (1) above
}
});
Note that this will still have the unordered problem. If you need sequential dynamic loading check out something like require.js
If the code needs to be fired from a JavaScript function then you can get rid of the document.write, in favor of creating new script objects, and appending to the head tag.
<?php
foreach($js_files as $filename){
if(trim($filename) != ''){
echo 'var s = document.createElement("script");';
echo 's.type = "text/javascript";';
echo 's.src = "' . $filename . '";';
echo 'document.getElementsByTagName("head")[0].appendChild(s);'
}
}
?>
You have to escape the code "" in if( trim($filename) <> "" ) because the " breaks the javascript string.

How to inject code from one text file into an HTML page

I have a series of large html pages in development, each uses a common structure: header / content / sidebar.
Header and sidebar sections have code common to all pages. Only content changes.
During the development phase, I want to be able to make changes to the header and sidebar once and see the results replicated on all pages without having to edit each page separately.
I've done a bit of googling, and the simplest solution seems to be to create 2 separate text files with the code for the header and sidebar sections, and then inject this at the appropriate points in the HTML pages I'm editing.
I know this is not recommended for a live project, as it would dramatically increase the load times, but for dev work it would save me a lot of time.
Would you agree? If so, anybody have any idea what the simplest way to do this is?
Thanks
You would be better to do this with some sort of server-side technology, like PHP. This would make the impact on loading times negligible as the pages would be concatenated before they were sent to the browser.
You would accomplish it by doing something like this:
<?php require('header.php'); ?>
<!-- Main content goes here -->
<?php require('sidebar.php'); ?>
And then have the files header.php and sidebar.php in the same directory as the main files.
Use some sort of serverside templating languate that would allow for you to include files within each other.
If, despite the other answers, you insist on doing this from JavaScript, the following is a module I use :
(function xload (slctr) { //================================================== xload ===
function xloader (src, dst) {
if (arguments.length == 1) {
dst = src;
src = dst.getAttribute ('data-source') || '';
}
var req;
try {
src = src.match (/^([^]*?)(!)?(?:\[\[([^]*?)\]\])?$/);
(req = new XMLHttpRequest ()).open ('GET', src[1], !src[2]);
req.onreadystatechange = function (ev) {
if (this.readyState === 4) {
if (typeof dst == 'function')
dst (req);
else {
dst[dst.tagName == 'TEXTAREA' ? 'value' : 'innerHTML'] = this.responseText;
[].forEach.call (dst.getElementsByTagName ('SCRIPT'), function (s, i) {
var script = document.createElement ('script');
script.innerHTML = s.parentNode.removeChild (s).innerHTML;
document.body.appendChild (script);
})
}
}
};
src[3] && req.overrideMimeType &&
req.overrideMimeType (src[3]);
req.send (null);
} catch (err) { console.log ('xloader error : ', err); }
}
[].forEach.call (document.querySelectorAll (slctr), function (el) { xloader (el); });
}) ('[data-source]'); //------------------------------------------------------ xload ---
Any element, a div for example with a data-source attribute is processed. The data-source specifies the url of the file to be included. When he Ajax request completes, the entire contents of the div are replaced with the text fetched. The data-sourc url may optionally be followed by a ! indicating synchronous load and then by a Mime type enclosed in [[ and ]]
Any scripts in the loaded text are extracted and injected into the document body.
Error conditions are reported on the console.
The module is entirely standalone and processes all elements containing the data-source attribute. It should, of course be loaded after the HTML text of the page.

Categories