We can create an object Xmlhttprequest to make an HTTP request to
one Server-side language, who will be in charge of reading/writing the file. This example will be in PHP.
With Javascript embedded in the HTML file, we call the Ajax function when loading the document and submitting the form:
<!doctype html>
<html>
<head>
<title>Exemplo Ajax só com JavaScript</title>
</head>
<body>
<form name='myForm'>
Trocar ano: <input type='text' id='ano-doc' />
<input type='button' onclick='ajaxFunction()' value='Ajax!'/>
</form>
<div id='ajaxDiv'>Resultado do Ajax</div>
<script language="javascript" type="text/javascript">
/**
* Inspirado em http://www.tutorialspoint.com/php/php_and_ajax.htm
*
* @param iniciar Boolean Usando para inicio da página ou envio do formulario
*/
function ajaxFunction( iniciar ) {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Não tem jeito
alert( 'Seu browser quebrou!' );
return false;
}
}
}
// Listener que recebe retorno do Ajax
ajaxRequest.onreadystatechange = function() {
if( ajaxRequest.readyState == 4 ) {
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
if( iniciar ) {
ajaxRequest.open( "GET", "ajax-exemplo.php" , true );
ajaxRequest.send( null );
} else {
// Capturar valores e fazer chamada Ajax
var ano_doc = document.getElementById('ano-doc').value;
var queryString = "?ano=" + ano_doc ;
ajaxRequest.open( "GET", "ajax-exemplo.php" + queryString, true );
ajaxRequest.send( null );
}
}
// Roda script ao carregar a página
ajaxFunction(true);
</script>
</body>
</html>
The request will be made to the file ajax-exemplo.php
, that will return a result or other as a submission form or not:
<?php
function escreverArquivo( $arquivo, $ano ) {
// Let's make sure the file exists and is writable first.
if ( is_writable( $arquivo ) ) {
// Write $somecontent to our opened file.
$content = file_get_contents( $arquivo );
$somecontent = str_replace( '{ano}', $ano, $content );
file_put_contents( $arquivo, $somecontent );
echo 'Arquivo atualizado.';
} else {
echo "O arquivo $arquivo não tem permissão de escritura.";
}
}
function lerArquivo( $arquivo ) {
$file = new SPLFileObject( $arquivo ); // http://stackoverflow.com/a/9897022/1287812
echo '<pre><code>';
foreach( $file as $line ) {
echo $line;
}
echo '</code></pre>';
}
$arquivo = "ajax-exemplo.txt";
if( empty( $_GET['ano'] ) ) { // Primeiro load da página
lerArquivo( $arquivo );
} else { // Formulário enviado
escreverArquivo( $arquivo, intval( $_GET['ano'] ) );
}
Finally, the file ajax-exemplo.txt
, where {ano}
will be replaced by the value sent by the form:
GNU GENERAL PUBLIC LICENSE
Version 2, Junho {ano}
The example of this answer will change the text file only once, since the str_replace()
you won’t find {ano}
after the first replace.
There is a funny but very limited project to read and write files on the client side: jQuery.twFile. I won’t include it in the answer because to date it requires applets for Webkit browsers (Opera, Safari, Chrome) and doesn’t work in Internet Explorer. But stay here and keep an eye on this :)
– Zuul
Thanks for the help!
– Junior CT
Excellent response!
– Diego Souza