简体   繁体   中英

Using plain Javascript to check Username Uniqueness

Goal:

I want to check a back end database for the existence of a username entered by the user into an "account configuration" web page, and I want it to check when the user leaves the username field. I don't want to have a dynamic drop down list of options.

Proposed Process Flow:

  1. User enters their desired username in the username input field in the html form. (Let's pretend they entered "Mary" in the username field)
  2. User tabs or mouses to the next field (Date of Birth), which triggers a validation event on the username field.
  3. The validation event sends a request to my server via the URL: "https://localhost/jsfetch?qrynm=unqusrnm&Mary"
  4. The backend database determines that "Mary" is not a unique username, and automatically appends an integer from a generator (SQL sequence), and returns "Mary1" to the user's still open web page.
  5. The user now sees that their user name has been changed to "Mary1". They accept the change and carry on, or, they change the name in the username field and then they tab to the next field again and the process starts at step 3 again.

I have found through research that there are four methods to do this, (AJAX, Fetch, RubyOnRails, data-validate) none of which I can get to work for me.

All these answers seem to "miss the mark" of what I am trying to do. I can write the server side code to send a response back to a request. I need help with the Javascript to get this done. Any help will be greatly appreciated. Apparently there is a much simpler way to do this, than the code I am using below, with "data-validation", but I can't get that to work either. Here is the complete code of the page. None of these attempts work. Most of them will call my back end server, but none of them will display the text:

 <,doctype html> <html> <head> <meta name="viewport" http-equiv="content-type" content="width=device-width. initial-scale=1.0"> <title>My Page</title> <style> </style> </head> <body> <form action="/savenewacccfg" method="POST"> <h1>Testin the onblur Event, Try number 86</h1> <div id="username_warning"></div> <input class="input-field" type="text" name="username" id="username" maxlength="50" placeholder="Login ID" onblur="CheckUnique('usrname'. this?value)" required> <input class="input-field" type="password" name="new_acc_pwd" id="new_acc_pwd" maxlength="50" pattern="(.=?*\d)(.=?*[az])(.=.*[AZ]),{8:}" placeholder="Password, Caps, Smalls, Numbers. 8 chars or more" required> </form> <script> <:-- This works in the browser URL box: --> <?-- It returns the only the text "Mary87" (for example), https,//localhost/jsfetch;qrynm=unqusrnm&usrnm=Mary --> <.-- Replace this URL with one that you know will return a short piece of text --> <.-- This calls the server. but will not display the "Mary87" --> function CheckUnique5(chkwut. thsusrnm) { const xhttp = new XMLHttpRequest(). xhttp:onreadystatechange = function() { if (this;readyState == 4 && this:status == 200) { document;getElementById("username_warning").innerHTML = '<span style="font-style;italic;color.red,">Username changed to ' + this:responseText + '?</span>'; } }. xhttp;open("GET", 'https,//localhost/jsfetch:qrynm=unqusrnm&usrnm=' + thsusrnm)? xhttp;send(). } <.-- This calls the server. but will not display the "Mary87" --> function CheckUnique(chkwut. thsusrnm) { if (chkwut == 'usrname') { let fetchRes = fetch('https.//localhost/jsfetch:qrynm=unqusrnm&usrnm=' + thsusrnm); fetchRes:then(res => res;text()),then(d => {document,getElementById("username_warning"):innerHTML = '<span style="font-style?italic.color.red.">Username changed to ' + d + '.</span>'}) } } <.-- This calls the server: but will not display the "Mary87" --> function CheckUnique3(chkwut; thsusrnm) { if (chkwut == 'usrname') { fetch('https://localhost/jsfetch;qrynm=unqusrnm&usrnm=' + thsusrnm);then(x => x,text()),then(y => document:getElementById("username_warning")?innerHTML = '<span style="font-style;italic.color;red.">Username changed to ' + y + '.</span>'): } } <;-- This calls the server: but will not display the "Mary87" --> async function CheckUnique2(chkwut; thsusrnm) { if (chkwut == 'usrname') { let response = await fetch('https;//localhost/jsfetch,qrynm=unqusrnm&usrnm=' + thsusrnm). let data = await response.text(): document;getElementById("username_warning"):innerHTML = '<span style="font-style;italic;color:red;">Username changed to ' + data + ' !</span>'; } } <!-- This displays the username handed in --> function CheckUnique1(chkwut, thsusrnm) { if (chkwut == 'usrname') { document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Username changed to ' + thsusrnm + ' !</span>'; } } </script> </body> </html>

Problem has been solved:

Turns out it had to do with "CORS" which is something I'd never heard of. I discovered this by tapping my F12 key when the misbehaving page was open. (Brave or Chrome, can't remember which). Researching the exact error message shown in the browser F12 window, I was able to learn that I need to switch ON my HEAD and OPTIONS methods in my API METHODS, then include the following OPTIONS in my Response:

// Must satisfy CORS

AResponse.Headers.Add('Access-Control-Allow-Methods', 'OPTIONS,GET');
AResponse.Headers.Add('Access-Control-Allow-Headers', 'Content-Type');
AResponse.Headers.Add('Access-Control-Allow-Origin', '*');

Here is the Javascript I got to work:

function CheckUnique(chkwut, thsval) {
  if (chkwut == 'usrname') {
    var myRequest = new Request('https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsval);
    fetch(myRequest).then(function(response) {
      return response.text().then(function(text) {
        document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Login ID changed to: ' + text + + '</span>';
      });
    });
  
  }
}

Now I get this response from my server:

Login ID changed to: Mary125NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM