Reputation: 65
I am trying to read and write into text files using jQuery. I have already written the function to read a file; but I can't do is write into a file. I have 2 files, read.txt
and write.txt
, in the same folder as the code.
The two jQuery functions (below, with surrounding server-side Perl code) are:
<!-- language: perl -->
my $script = qq{
\$(document).ready(function() {
\$("#readFile").click(function() {
\$.get('read.txt', function(data) {
\$("#container").val(data);
}, 'text');
});
});
\$.ajax({
url: './test.pl',
data: {
'myString' : "#cont"
},
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
});
};
my $q = new CGI;
print $q->header;
print $q->start_html(
-title => "Read a File",
-style => {-src => 'css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet'},
-script => [
{-src => 'js/jquery-1.9.1.js'},
{-src => 'js/jquery-ui-1.10.3.custom.js'},
],
);
print $q->start_form;
print $q->textfield(
-style => 'font-family:verdana;width:300px;font-size:13px',
-id => 'container',
-value => '',
);
print $q->button(
-id => 'readFile',
-name => 'submit_form',
-value => 'Read',
);
print $q->textfield(
-style => 'font-family:verdana;width:300px;font-size:13px',
-id => 'cont',
-value => '',
);
print $q->submit(
-id => 'writeFile',
-name => 'submit_form',
-value => 'Write',
);
print $q->script($script);
print $q->end_html;
test.pl
use CGI ();
my $cgi = CGI->new;
print $cgi->header;
my $string = $cgi->param("myString");
open (FILE, ">", "./write.txt") || die "Could not open: $!";
print FILE $string;
close FILE;
Upvotes: 1
Views: 24160
Reputation: 7063
You can't write in files with Javascript/jQuery for security reasons because, if you could, a user would be able to change easily the file url to edit with his console and create consequent damages. For more details, you can have a look to this page.
In order to solve your problem, I think the best way to do is send to a remote php file, using ajax, the content of the files you want to update. Then, this file will do the update.
Upvotes: 9