Praxbyr
Praxbyr

Reputation: 15

Write line to text file with AJAX XMLHttpRequest

Here is my javascript function that reads from the file every second and outputs it:

var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
    var lines;
    var alltext;
    request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4) {  // document is ready to parse.
            if (request.status === 200) {  // file is found
                allText = request.responseText;
                lines = request.responseText.split("\n");
                document.getElementById("test").innerHTML = "";
                for (i in lines) {
                    document.getElementById("test").innerHTML += lines[i] + "<br>";
                }
            }
        }
    }
    request.send();
}
timer = setInterval(ajaxcall, 1000);

I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:

function chat() {
    request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.send("\n" + document.getElementById("chatbox").value);
}

However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.

Upvotes: 0

Views: 4129

Answers (1)

Borre Mosch
Borre Mosch

Reputation: 4564

You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.

Upvotes: 1

Related Questions