I am trying to get a response from a local file and display it. However, the response text changes back to the original text. Any help would be appreciated.

<script>
    function getMsg(text) {
        if (text.length == 0) {
            document.getElementById("msg").innerHTML = "";
            return;
        } else {
            document.getElementById("msg").innerHTML = "sending request";

            var xhttp = new XMLHttpRequest();
            var filepath = "";
            if (inputText == "File1") {
                filepath = "file1.txt";
            } else if (inputText == "File2") {
                filepath = "file2.txt";
            }
            xhttp.open("GET", filepath, true);

            xhttp.send();
            xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                alert(this.response);
                document.getElementById("msg").innerHTML = this.responseText;
            } else {
                document.getElementById("msg").innerHTML = "failed";
            }
        };    
    }
}
</script>
<body>
<form onsubmit="getMsg(this.file.value)">
        <label for="file">File:</label>
        <input type="text" name="file" id="file">
        <button type="submit">Get</button>
    </form>
</body>

2 Answers

0
Musa On

This is because you form submits normally along with your ajax and reload the page. You can prevent the form from submitting by returning false from your onsubmit handler.

<form onsubmit="getMsg(this.file.value); return false">
0
k3lly.dev On

Welcome to Stackoverflow, by reading your code I noticed you got two main issues.

Avoid using innerHTML, it's a bad practice.

When you use innerHTML, even if your string variable is only text (no HTML tags, etc), the content is parsed by JavaScript which takes time, it might not be significant in a small app like this, but in bigger apps this has a big impact in performance.

Use innerText.

You are not preventing the default behavior of your form.

When using AJAX request, the best approach for this is to set an event listener to the form like this:

Your HTML:

<form id="file_select"><!-- Add an id to identify the form -->
        <label for="file">File:</label>
        <input type="text" name="file" id="file">
        <button type="submit">Get</button>
</form>
<div id="msg"></div>

You can add an event listener in JavaScript like this:

document.querySelector("#file_select").addEventListener("submit",(event)=>{
   event.preventDefault();
   //Your code
});

The preventDefault() function prevents the window redirection to the action attribute of your form. (Default behavior)

Keeping code clean, reusable and simple.

This is the same function with cleaner code, you should try keeping your code easy to read so when you come back to it you understand everything perfectly.

const message = (text) =>{
  document.querySelector("#msg").innerText = text; //The message div
};
document.querySelector("#file_select").addEventListener("submit",(event)=>{
 event.preventDefault();
  let fileValue = event.target.file.value; //The value of the file
  if (fileValue != "") { //If value not empty
      var xhttp = new XMLHttpRequest();
      var filepath = (fileValue === "File1" ? "file1.txt" : (fileValue === "File2") ? "file2.txt" : "");
      message("Filepath is: "+filepath);
      xhttp.open("GET", filepath, true);
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
              message.innerText = this.responseText;
          } else {
              message.innerText = "failed";
          }
          xhttp.send();
      }
  } else { //If input is empty
      message("Invalid file.");
  }
});
<form id="file_select">
        <label for="file">File:</label>
        <input type="text" name="file" id="file">
        <button type="submit">Get</button>
</form>
<div id="msg"></div>

Note: You can use message("text") to output the result of your AJAX request. It's up to you how to fit this to your expected behavior. Hope this helps you.