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
});
Related
I would like to retrieve data from specific cells in a local Excel sheet using Javascript and then output it on an HTML page. My function would be something like readData(row, col).
For example:
Cell 1A = "hello"
<h4><script>readData(1, A)</script></h4> will show as "hello" on my page.
Every solution I have seen has involved uploading the file first (example below from the read-excel-file package), but my Excel file is already a local file within my project.
<script>
var input = document.getElementById('input')
input.addEventListener('change', function() {
readXlsxFile(input.files[0]).then(function(rows) {
// `rows` is an array of rows
// each row being an array of cells.
})
})
</script>
My guess is you are referring to this project?
https://gitlab.com/catamphetamine/read-excel-file
I tried using the Node.js example. It works out of the box. The examples for a direct website integration are broken. The project seems still alive, but I would scan the code to decide if to trust the author with your data.
Here how to fix the example (I have no idea for what cases it works!):
Go into the "website" folder. The index.html is a example how to use it. Unfortunately the "read-excel-file.min.js" is missing in the repo. You can download it here (view-source:https://catamphetamine.gitlab.io/read-excel-file/read-excel-file.min.js). Put it in the folder and it works.
Maybe someone has a better code for this?
EDIT (Above answer not technically wrong but does not answer the post):
What you want is not possible to security reasons! Just imagine your javascript (client!) code:
inputfile="test.xlsx"
I could edit this in my browser to
inputfile="super_secret_files_on_server.xlsx"
Solution: You could run node.js code on your server and solve it this way, or the user has manually upload a file from his computer. Or use a server side programming languages like php.
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;
});
}
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
I need to have the functionality in the server side in order to hide the implementetion to the final user.
I didn't find a topic with this kind of solution.
I have a .js file with functions I use within the html5 file.
The js files are "called" in the html by using the script tag, but through the url the user can track them and see the .js file content. I don't want this to happen.
$getScript() does the job, but again the url can be cathched, thus the file content too. Much the same with $ajax function.
Everything work ok, but I want to hide the js content.
The .js file is something like this:
var x, x,....
function A(){...}
function B(){...}
and so on, I use A(), B() functions in the html.
Which is the best approach to get the content file from the server without doing the url visible?
Server: nodejs. (I send some json files through socket.io correctly, but I don't know how to achieve this other issue.
Thanks in advance, best!
If you are sending sensitive information to the client then you are doing it wrong. No matter if the client has the URL to the script, they will still be able to find it if they are determined as long as it is sent to their computer.
Find a different way to accomplish what you are trying to do without sending sensitive information to the client. It is not safe.
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?.