menardmam
menardmam

Reputation: 9986

Read/write to file using jQuery

Is there a way to get jQuery to get information to and from a file? Is it possible? How?

Upvotes: 65

Views: 272355

Answers (5)

Paolo Bergantino
Paolo Bergantino

Reputation: 488714

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.

Upvotes: 79

Josh Stodola
Josh Stodola

Reputation: 82523

If you want to do this without a bunch of server-side processing within the page, it might be a feasible idea to blow the text value into a hidden field (using PHP). Then you can use jQuery to process the hidden field value.

Whatever floats your boat :)

Upvotes: 1

Javier
Javier

Reputation: 62681

both HTML5 and Google Gears add local storage capabilities, mainly by an embedded SQLite API.

Upvotes: 16

jonstjohn
jonstjohn

Reputation: 60346

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.

Upvotes: 9

Clyde
Clyde

Reputation: 8145

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.

Upvotes: 5

Related Questions