javascriptflaskxmlhttprequest-level2

Live code editor - cannot delete first character (using XMLHttpRequest and flask)


I have a live code editor, and I cannot delete the first character, if I select the whole text, and press delete or backspace, it do not do anything.
What can I do?
Html:

<!doctype html>
<html>
 <head>
  <title>Live Code editor</title>
 </head>
 <body>
  <textarea id="text"></textarea>
 </body>
</html>

Javascript:

let text=document.getElementById('text')
let xhr=new XMLHttpRequest()
function sendRequest(tobeSend,writeResponse) {
 xhr.open('POST','/files/file.txt',false);
 if(!tobeSend) { //if `tobeSend` not null
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   }
 xhr.send(tobeSend);
 if(writeResponse) {
  text.value=xhr.responseText;
   }
 }

sendRequest(null,true)

text.addEventListener('input',function(e){sendRequest(text.value,false)})
        setInterval(function(){let c={start:text.selectionStart,end:text.selectionEnd};sendRequest(null,true);text.setSelectionRange(c.start,c.end)},200)//fresh the code every 200 millisecond

Python/flask:

@app.route('/files/file.txt')
def file():
 if request.method=='POST':
  if request.form.text:
   with open('files/file.txt','w') as f:
    f.write(str(request.form.text))
  with open('files/file.txt') as f:
   return f.read()

Note: I know, I should not use sync xhr, but when I send an async request, and I write some text, the returning async function delete the writed text (if somebody know an async solution, I would really appreciate it).


Solution

  • I have since discovered the problem:
    When I send at the data "text=", the request.form.get("text") returns '', and tha boolean value is False.
    So I changed the code as below:

    @app.route('/files/file.txt')
    def file():
     if request.method=='POST' or request.form.get("text")=='': #intead of `if request.form.get("text")`
      if request.form.text:
       with open('files/file.txt','w') as f:
        f.write(str(request.form.text))
      with open('files/file.txt') as f:
       return f.read()