Search code examples
javascripthtmlxmlhttprequest

Reading from a text file using xmlhttp


I want read a word from a text file and use it to verify a password. Of course I realise this is not in any way secure and would never be used in the real world, but it is an assignment for a college course that I have to do. Every time I click submit, I am brought to the page 'messing.html', regardless of whether the password is correct or not... Can somebody please help?

<!DOCTYPE html>
<html>


<body>

<form name="login" onSubmit="return validateForm();" action="messing.html" method="post">
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var user_input = document.login.pword.value;


        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","books.txt",false);
        xmlhttp.send();
        var y =xmlhttp.responseText;




        if (user_input == y){
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your password");
            return false;
        }
  }
</script>

</body>

</html>

Solution

  • The problem is the onsubmit. Because you don't prevent the default action of the form. Your form is sent to messing.html and that will be loaded.

    You need to prevent the default action on the form when you want to use xmlHTTPRequest.

    function validateForm(e) {
         ....
       e.preventDefault(); //<--- magic
    

    }

    on a side note. Using synchronous xmlHTTPRequest is considered bad practice and not allowed in modern browsers, since it could hang the browser if no response is available or takes a long time to load. In this case switching to asynchronous is simple.

    function validateForm(e) {
        var user_input = document.login.pword.value;
    
    
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","books.txt",true); //changed to true
    
        xmlhttp.onreadystatechange = function(){
         if (this.status == 200 && this.readystate == 4)
         {
           var y =xmlhttp.responseText;
           if (user_input == y){
              location.href = "messing.html";
    
           }
           else {
              alert ("Login was unsuccessful, please check your password");
              return false;
           }
         }            
        }
        xmlhttp.send();
        e.preventDefault();
    

    }