0

I am adding some form validation and updating the visibility of a notification depending on the status code of an http request using:

function isValidEndpoint()
{
    var xmlHttp = null;
    var myurl = "/restyendpoint/" + document.getElementById("endpoint").value;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", myurl, true );
    xmlHttp.send( null );
    if (xmlHttp.status == 409) {
        document.getElementById("sucnot").style.visibility="hidden";
        document.getElementById("warnot").style.visibility="visible";
    } else {
        document.getElementById("sucnot").style.visibility="visible";
        document.getElementById("warnot").style.visibility="hidden";
    }
}

When I load the page the elements are both invisible, on typing the first character I get the "That endpoints free" message (as the first character entered doesn't exist in the db). From that point the visibility of the notifications doesn't change, even though I can confirm correct request/response from the "restyendpoint" validation.

J0hnG4lt
  • 4,337
  • 5
  • 24
  • 40
  • Did you add console lines and see what the status is? Also synchronous requests are a bad idea. – epascarello Jan 02 '14 at 17:24
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Musa Jan 02 '14 at 17:27
  • 1
    Status is good: 409 and 200 for existing and nonexisting enpoints, as expected. I thought xmlHttp.open(,,true) was for "use async": will rtfm, thanks. – J0hnG4lt Jan 02 '14 at 17:28

1 Answers1

0

Having been provided with Prior art by @Musa. I amended my code as follows and it now works:

function isValidEndpoint()
{
    var xmlHttp = null;
    var myurl = "/restyendpoint/" + document.getElementById("endpoint").value;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState === 4) {// request is done
            if (xmlHttp.status === 409) {// endpoint exists
                document.getElementById("sucnot").style.visibility="collapse";
                document.getElementById("warnot").style.visibility="visible";
            } else {//endpoint doesn't exist
                document.getElementById("sucnot").style.visibility="visible";
                document.getElementById("warnot").style.visibility="collapse";
            }
        }
    };
    xmlHttp.open( "GET", myurl, true );
    xmlHttp.send( null );
}

So, setting async to true in the request, the xmlHttp object needs to check the status when it returns. What it was doing was immediately checking the status, and defaulting to always display a particular notification.

Community
  • 1
  • 1
J0hnG4lt
  • 4,337
  • 5
  • 24
  • 40