Search code examples
javascriptajaxauthenticationxmlhttprequestajaxform

AJAX POST XHR Failure - Why is this not working?


I am pulling my hair out here. I have checked several other posts that were related to issues with POST and AJAX, but none I found were helpful. I cannot figure out why this is not working.

I keep getting the error:

Uncaught TypeError: Cannot read property 'value' of null at loginRequest (loginRequest.js:3) at HTMLButtonElement.onclick (main.html:325)

Here is the form on the ".html" page (minus my class calls):

<form id="loginform"> 
 <div>
  <label for="login_userid"><b>Username</b></label>
  <input id="login_userid" type="text" placeholder="Enter Username" name=login_userid" 
                                            autocomplete="username" required>

  <label for="login_psw"><b>Password</b></label>
  <input id="login_psw" type="password" placeholder="Enter Password" name="login_psw" 
                                           autocomplete="current-password" required>

  <button onclick="loginRequest()">Login</button>
  
</div>

Then here is the ".js: file, which I am declaring in the head of the ".html" file:

function loginRequest() {
{
    var login_userId = document.getElementById('login_userId').value;
    var login_ps = document.getElementById('login_psw').value;
    const bcrypt = dcodeIO.bcrypt;
    var login_psw = bcrypt.hashSync(login_psw, 12);

    var xhr;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE 8 and older
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var data = "login_userId=" + login_userId + "&login_psw=" + login_psw;
    xhr.open("POST", "https://dfs-coach.com/assets/php/login.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(data);
    xhr.onreadystatechange = display_data;
    function display_data() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                //alert(xhr.responseText);
                document.getElementById("login_result").innerHTML = xhr.responseText;
            } else {
                alert('There was a problem with the request.');
            }
        }
    }
 }

}

Note: bcrypt.js is also declared in head, after loginrequest.js. The '#login_result' element is at the top of the html page (login form opens in a modal)

I cannot figure out where my screw up is with this one.. I know it is going to be something I did, i.e., a syntax error, scope issue,. etc... but I cannot find it.

The error returns that the username is null, which is difficult to believe since A: I type it in before hitting the button to trigger the function, and B: it is a required field, so I cannot hit the button if it is not filled.

However, I get that TypeError from above and then the browser tacks the correct info onto the end of the current URL in plain text and it appears in my address bar. This happens both locally and from an active web server.

The Dev Panel shows this as an "Info" entry:

Navigated to https://www.dfs-coach.com/main.html?login_userid=MyUsernm&login_psw=PwformyUser

(Info typed into form: 'MyUsern' and 'PwformyUser')

Feel free to see the live demo of this error: https://dfs-coach.com/main.html

I would appreciate any help at all on this one.

Thanks

P.S.: I have also tried using both '.innerHTML' and innerText' instead of 'value' on the Dom elements, and also sending the form data as FormData and json. All to no avail.


Solution

  • There two issues which can easily be fixed I found in the code snippet in the question:

    1. In the 1st line of the function you tried to find an element by the id: login_userId, however the element is named login_userid in the HTML code, Make sure that the capitalization is the same otherwise document.getElementById won't find the correct element

    2. Another small mistake in the 4th line of the code where you try to hash login_psw bcrypt.hashSync(login_psw, 12); however that variable does not exist yet. I believe what you are trying to do is hash the login_ps variable made a couple lines earlier

    I also suggest you to put the function immediately after the xhr.onreadystatechange

    Code that should work:

    <body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/bcrypt.min.js"></script>
    <div id="loginform"> 
        <div>
         <label for="login_userid"><b>Username</b></label>
         <input id="login_userid" type="text" placeholder="Enter Username" name=login_userid" 
                                                   autocomplete="username" required>
       
         <label for="login_psw"><b>Password</b></label>
         <input id="login_psw" type="password" placeholder="Enter Password" name="login_psw" 
                                                  autocomplete="current-password" required>
       
         <button onclick="loginRequest()">Login</button>
         
       </div>
    </div> 
    </body>
    <script>
    function loginRequest() {
        {
            var login_userId = document.getElementById('login_userid').value;
            var login_ps = document.getElementById('login_psw').value;
            const bcrypt = dcodeIO.bcrypt;
            var login_psw = bcrypt.hashSync(login_ps, 12);
        
            var xhr;
            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                xhr = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // IE 8 and older
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var data = "login_userId=" + login_userId + "&login_psw=" + login_psw;
            xhr.open("POST", "https://dfs-coach.com/assets/php/login.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(data);
            xhr.onreadystatechange = function display_data() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        alert(xhr.responseText);
                    } else {
                        alert('There was a problem with the request.');
                    }
                }
            }
         }
        }
         </script>