Write current time in a .txt file

1

How to make an online post of a variable in a given TXT? I tried the following, but it did not work:

function post(theUrl)
{
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "POST", theUrl, false );
    xmlHttp.send("Hora Atual" + $hora);
    return xmlHttp.responseText;
}

post("http://www.example.com/aviso.txt");
    
asked by anonymous 28.05.2014 / 16:57

3 answers

5

javascript is a client-side language and you can not interact with files in this way.

You need some language server-side for example: #, asp.net

    
28.05.2014 / 17:32
5

If what you are trying to do is generate a .txt the answer is: Yes, it is possible.

HTML5 allows the use of the download attribute in <a> tags, which does nothing more than force the content of that link to be downloaded. Example:

HTML:

<a href="#" download="data.txt" id="download">Download da data</a>

JavaScript:

var mt, data, download;
mt = 'data:text/plain;charset=utf-8,';
data = new Date();
download = mt + encodeURIComponent(data);

document.getElementById('download').setAttribute('href',download);

Exemplo

More about the download attribute:

  • Can be used to download generated images on the client side via base64 ;
  • Does not override HTTP headers (if a header directive conflicts with it, the header prevails);
28.05.2014 / 20:27
1

By your very brief explanation, what I could understand is that you simply want to record a certain timestamp in a text file.

If you first thought about AJAX, you should either at least keep in mind that there needs to be a server side application (PHP, ASP, Python ...) to handle the filesystem , effectively creating this file.

So what's the point of going all that way, involving JavaScript, blocking your application, if a simple link pointing to a particular URL responsible for creating the file is enough? An example with PHP is seen to be popular and I do not know what your server language is:

<a href="/path/to/my/resource.php">Gerar Aquivo</a>

<?php file_put_contents( 'aviso.txt', date( 'd/m/Y - H:i:s' ) . "\n", FILE_APPEND );

Disregarding write permissions checking, I solved a specific problem in two lines, one of HTML and one of PHP.

If I'm wrong, please edit your answer and provide more details. Do not help us help you.

    
29.05.2014 / 19:06