Is there a way to get jQuery to get information to and from a file? Is it possible? How?
- 2Can you not write the answer to a field within the HTML?Darryl Hein– Darryl Hein2009-02-24 18:16:08 +00:00Commented Feb 24, 2009 at 18:16
- That 's not true anymore. but the access you can get through javascript are restricted to what the user allow you.Kiwy– Kiwy2013-12-16 09:02:32 +00:00Commented Dec 16, 2013 at 9:02
- 1The sandbox prevents direct file access for security reasons. You can use the HTML5 File API to allow the user to select files from a file dialog.Evan Plaice– Evan Plaice2016-01-21 15:02:11 +00:00Commented Jan 21, 2016 at 15:02
5 Answers
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.
6 Comments
You will need to handle your file access through web programming language, such as PHP or ASP.net.
To set this up, you would:
Create a script that handles the file reading and writing. This should be visible to the browser.
Send jQuery ajax requests to that script that either write data or read data. You would need to pass all of your read/write information through the request parameters. You can learn more about this in the jQuery ajax documentation.
Make sure that you sanitize any data that you are storing, since this could potentially be a security risk. However, this is really just standard flat-file data storage, and is not necessarily that unusual.
As Paolo pointed out, there is no way to directly read/write to a file through jQuery or any other type of javascript.
Comments
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.