Change file content with ajax

-1

Hello, first of all, I would like to clarify that I looked so much here in the stack, as in other sites something that answered my question, but I did not find it. My question is, how can I rewrite the contents of a JSON file from the server using AJAX? In case, I can get the contents of it and use it in the browser normally, but when I change something in the browser, I would like to save / overwrite the changes in the original file.

Current Code:

JSON

[{
    "nome":"Borin Gnur",
    "profissao":"Bibliotecário",
    "imagem":"img/borin.png"
}, (...)]

JS

var personagensJSON;
function recuperaPersonagens(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            return personagensJSON = JSON.parse(this.responseText);  
        }
    };
    xhttp.open("GET", "personagens.json", true);
    xhttp.send();
    //selecaoPersonagem();
}
    
asked by anonymous 31.10.2017 / 18:37

1 answer

1

Your problem is:

  

To change something in the browser, I would like to save / overwrite the changes in the original file.

What you have to do is make the changes in the browser, and then send (possibly via AJAX) the changed file to the server for the server to save (probably using one of the HTTP POST, PUT, or PATCH verbs).

The server should provide a service for this purpose, as well as dealing with proper authentication and authorization issues (to prevent malicious users from messing with server files).

You can not save directly without being through the server. The reason is that the file is modified in the browser of a certain computer (or cell phone or similar) and it should be saved in the file system of the computer Y . There is no way to make data that is X appear in Y without it being sent somehow from the X device to the < and the best way to send them is through HTTP, which is the protocol already used by the browser running on X in a site made available via HTTP by the server and .

    
31.10.2017 / 20:45