include() like function in javascript - javascript

objective
I need a function that simply takes all the code from another file and pastes the code in the calling file.
possible solution
a function that works like the include() function in PHP.
reason
When I had hosting, I used the php function include("filename.html") to include things like headers and footers, in all the files on the website. This made life a lot easier!
Now I don't have hosting, because I am working on another site, and I am using Github Pages and thus, I can't use PHP. I need to use only HTML, JS and jQuery etc. So, I need a function that simply takes all the code from another file and pastes the code in the calling file.
Already tried
load() in jQuery.
<pre><script>
$(document).ready(function(){
$("#topbar").load("menubar.html");
});
</script></pre>
This question. I tried the accepted answer, but that didn't work for me.
Kindly help me with this issue.

You should consider setting up a build environment where you can compile your content locally before publishing it. This way, you can organize your code in different files (like in your case, with a header/footer that will always be included with different content files), compile locally to have the files automatically combined into a publish directory, and upload that instead.
This way, instead of e.g. sending 3 requests for a header, content and footer file, the header and footer are pre-compiled into the content file which can then be served with 1 request.
Personally I use Grunt as a build tool for purely static sites, together with a concatenation task (such as grunt-contrib-concat). There are several tutorials on the Grunt website, but you can see an example of how to configure a task for your specific problem here:
https://stackoverflow.com/a/12749861/351435

I do something like that :
var template = {
get: function (url, callback) {
if (this[url]) return callback(null, this[url]);
var self = this;
$.ajax({
"url": url,
"type": "GET"
})
done(function (html) {
self[url] = html;
callback(null, html);
})
.fail(callback);
}
};
after you just need to do that :
template.get("/menu.html", function (err, html, reason) {
if (err) return alert('An error is append : '+reason);
$("#topbar").html(html) // or append
});

I am assuming your scripts run in a browser.
Try the $.getScript function in jQuery.
`$.getMyScript("script.js", function(){
alert("Script executed.");
});`
Depending on how complex you want your solution to get, you could also look at http://requirejs.org/ for incorporating files/scripts/modules.
I believe this question is answered in full on How do I include a JavaScript file in another JavaScript file?.

Related

Cordova updating part of page

I created a login page with javascript. After a succesful the function loadMainActivity is called. As of now the contents are as follows:
async function loadMainActivity(){
document.getElementById("container").innerHTML = "This is a text.";
}
It works. However, now I want to load a complete HTML page upon a succesful login. I tried several plugins to this end. However, all of them require me to load a file. As I see it I have two options:
Provide an extra file with the app. This would enable my users to see the source, which I don't want.
Host the file on a server. This would require my users to have an active internet connection when using the app, which I also don't want, for now at least.
I thought about "stringifying" the HTML page and replacing "This is a text." with the obtained HTML string. That way I could keep the source closed. But this seems like a lot of extra steps. Besides, I cannot find a good method to do this stringification of HTML text.
How to solve this problem for a Cordova app?
I found that this can be done with the jQuery library, nothing specific to Cordova:
async function loadMainActivity(){
$.get("mainactivity.html", function( my_var ) {
document.getElementById("container").innerHTML = my_var;
});
}

JavaScript Basic Solution for Retrieving Files

I'm very new to JavaScript, so please be patient with me. I've got a CSV file published to the web via Google, which is updated periodically. I have the URL of the file, and I want to write JS code which will retrieve that file when an HTML page is loaded, then convert it into a string so I can manipulate it and scoop out the values I want to place in different elements. The problem is, I have no idea how to request items from different URLs. I'm guessing there's some built-in functionality in JS to do what I want, but I'm completely in the dark on how to find it. Care to help me out?
What you're looking for is the XMLHttpRequest, but I'd recommend using jQuery's $.ajax() function as it decreases the complexity of sending asynchronous requests.
You can use jquery $.ajax or better Fetch API or axios to get the file contents.
Then you need to process it by using something like Papa Parse.
PS. Papa Parse actually supports remote files directly so you can try that.
Sounds like what you're looking for is AJAX.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
doSomethingWith(this.responseText);
}
};
xhttp.open("GET", "http://url/file.csv", true);
xhttp.send();
You could also use jQuery's ajax function :
$.ajax({url: "http://url/file.csv", success: function(result){
doSomethingWith(result);
}});
This way, you get the result as a string which you can then use to retrieve the CSV values - look into the split function for instance.
Be aware that you will not be able to try this locally without a webserver, since your browser will not allow your Javascript to fetch files from your computer. Indeed, your browser implements a mechanism called CORS which restricts HTTP requests heading to a different domain.
Did you publish that .csv to google ? If so , can you program the file to be dumped to your web-content file?
I found I couldn't get files out of google drive with js, a lot of people had problems with this, then I tried to find a solution for it. So instead you can use platforms like github, or host on your server. Then the problem becomes way more straight forward.
I used python to grab the content I wanted , turn into .js file, or json file. Then use javascript to retrieve it.
var data = http://mywebsite.com/my_file.json
or script src = http://my_website/data.js /script
Sorry about the above. Stackoverflow messing with my js. The above is just an example of the script tag 'my_website' needs to be programmes in.
Great place to start with json , and other resource here
https://www.w3schools.com/js/js_json_intro.asp

Javascript: Save content to Text File (No complicated Server stuff / HTTPRequest )

I am working on a small Project for myself. I wont upload a webpage but only run the files on localhost on my machine(HTML,CSS,JAVASCRIPT)
function saveData() {
$.post("testFile.txt", "New Content of the File ");
}
function getData() {
$.when($.get("testFile.txt")).done(function(requestedData) {
alert(requestedData);
});
}
Ok so this is basically a dummy Project to explain my Problem.
The methods are called by two different Buttons with an "onclick" event.
First Button which calls "getData()" works fine. The testFile.txt is located right next to the Html and Javascript file, and the getData() method correctly alerts the content of the text file as a String.
My Problem:
How do I make the saveData() method work? Do I misunderstand the $.post() method? (https://www.w3schools.com/jquery/jquery_ajax_get_post.asp)
I read so many forums and topics the last days but none of them solves the problem the way I´d need it, because I don´t wanna do all these difficult looking http-requests things - just reading and writing to this file that is located in the same folder then all my html and javascript Files
Thanks :)
$.post is for sending a POST http request.
Client-side javascript doesn't have permission to write to a client machine.
This would be a massive security hole if it did.
However
You've tagged node.js in your question, which can write to the local filesystem:
var fs = require('fs');
fs.writeFile("testFile.txt", "New Content of the File", function(err) {
//done
});

Call a function in one Javascript file from another Javascript file?

I need to call a function in an external ".js" file from another ".js" file, without referencing the external file in the <head> tag.
I know that it is possible to dynamically add an external ".js" file to the which allows access to that file, i can do that like so...
var AppFile = "test/testApp_1.js";
var NewScript=document.createElement('script');
var headID = document.getElementsByTagName("head")[0];
NewScript.src = AppFile;
headID.appendChild(NewScript);
However...
this is no use to me as the external files need to be stand-alone files that run start-up procedures on...
$(document).ready(function()
{...}
so adding the full file dynamically has an unwanted affect. Also, i cannot pre-reference the external file in the <head> tag as it needs to be dynamic.
So, this external file "test/testApp_1.js" contains a function that returns a string variable...
function setAppLogo(){
var LogoFile = "test/TestApp_1_Logo.png";
return LogoFile;
}
I need access to either this function, or I could store the string as a global var in the external file... either way is fine, I just need access to the value in LogoFile without loading the whole external file.
This one has had me stumped for a few hours now so any ideas would be greatly appreciated.
You might benefit from having some sort of app.js file that contains global variables/values that you will want to use from lots of places. You should include this .js file on every page (and maybe minify it/concatenate it with other js if you want to be clever and improve performance). Generally these globals should be attached to some object you create such as var APPNAME = { }; with variables/functions on it that will be used from many places.
Once you have this, then the external '.js' file that you want to load, and the one you are currently in, can both access the global APPNAME variable and all its attributes/functions and use them as desired. This may be a better approach for making your javascript more modular and separatable. Hope this helps.
You want to load the file once jQuery has loaded using ajax, and then run the related script in the successful ajax function.
See jQuery's getScript function: http://api.jquery.com/jQuery.getScript/
$(document).ready(function(){
$.getScript("http://domain.com/ajax/test.js", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
//run your second script executable code here
});
});
It is possible to load the whole script through XHR (e.g. $.get in jQuery) and then parse it, perhaps using a regular expression, to extract the needed part:
$.get('pathtoscript.js', function(scriptBody) {
var regex = /function\s+setUpLogo\(\)\s*\{[^}]+}/g;
alert(scriptBody.match(regex)[0]); // supposed to output a function called
// 'setUpLogo' from the script, if the
// function does not have {} blocks inside
});
Nevertheless, it shall be noted that such an approach is highly likely to trigger maintenance obstacles. Regular expressions are not a best tool to parse JavaScript code; the example above, for instance, will not parse functions with nested {} blocks, which may well exist in the code in question.
It might be recommended to find a server-side solution to the problem, e.g. adding necessary script path or its part before the page is sent to browser.
I'm not sure this is a good idea but you can create an iframe and eval the file inside its 'window' object to avoid most of the undesired side effects (assuming it does not try to access its parent). Then you can access whatever function/variable you want via the iframe's window object.
Example:
function loadSomeJsInAFrame(url,cb) {
jQuery.get(url,function(res) {
iframe = jQuery('<iframe></iframe>').hide().appendTo(document.body);
iframe[0].contentWindow.eval(res);
if(cb) cb(iframe[0].contentWindow);
},'text');
}
loadSomeJsInAFrame('test/testApp_1.js',function(frameWindow) {
console.log(frameWindow.setAppLogo());
jQuery(frameWindow.frameElement).remove();
});
This will not guarantee that the sript in the file can not mess with your document, but not likely if it comes from a trusted source.
Also, don't forget to remove your iframe after you get what you need from it.
Ok, thanks everybody for all the input but i think that what I was trying to do is currently not possible, i.e. accessing a function from another file without loading that file.
I have however found a solution to my problem. I now query my server for a list of apps that are available, i then use this list to dynamically build the apps in a UI. when an app is then selected i can then call that file and the functions within. Its a bit more complex but its dynamic, has good performance and, it works. Thanks again for the brainstorming! ;)
It may be possible with the help of Web Workers. You would be able to run your script you've wanted to inject in kinda isolated environment, so it won't mess up your current page.
As you said, it is possible for setAppLogo to be global within "test/testApp_1.js", so I will rely on this statement.
In your original script you should create a worker, which references to a worker script file + listen to messages that would come from the worker:
var worker = new Worker('worker.js');
worker.onmessage = function (e) {
// ....
};
Then, in the worker (worker.js), you could use special function importScripts (docs) which allows to load external scripts in worker, the worker can also see global variables of these scripts. Also there is a function postMessage available in worker to send custom messages back to original script, which in turn is listening to these messages (worker.onmessage). Code for worker.js:
importScripts('test/testApp_1.js');
// "setAppLogo" is now available to worker as it is global in 'test/testApp_1.js'
// use Worker API to send message back to original script
postMessage(setAppLogo());
When it invokes you'll get the result of setAppLogo in you listener:
worker.onmessage = function (e) {
console.log(e.data); // "test/TestApp_1_Logo.png"
};
This example is very basic though, you should read more about Web Workers API and possible pitfalls.

jquery load to hide content

There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.)
So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too.
Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages":
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : "../../../secret_code.js",
dataType: "text",
success : function (data) {
$("#ajaxcontent").html(data);
}
});
});
</script>
1) Why can't I load a file from the root directory with ajax or load method?
2) Is there another way around?
PS: I'm putting the file in the root directory so people can't access it directly from their browsers...
1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers
2) try /secret_code instead of ../../../secret_code.js
What is your system setup? Are you using a CMS?
Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/
If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you.
Navigate to the URL, not the directory. Like
$.ajax({
url : "http://domain.com/js/secret_code.js",
..
Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer
Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
Try jQuery's $.getScript() method for loading external
Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar!
Security first
You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible.
You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js
If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles.
If you want to keep it secret, don't let it get to the browser.

Categories

Resources