0

Inside my Login class I have this piece of code :

state={email:'',passwordHash:''};

onButtonClick = () =>{
    if(this.state.email==='' || this.state.passwordHash==='')
        return;
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            console.log(this.responseText);
        }
    };
    request.open('GET', 'http://localhost:8080/login/'+this.state.email+'/'+this.state.passwordHash, true);
    request.send();
    if(String(request.responseText).match("true"))
    {
        console.log("Inside Match");
        window.location.href = '/home';
    }
};

And in the console I get this :

javascript string matching problem

As I'm getting true in the console, I should also get Inside Match in the console and then redirect, but that is not happening.

Can anyone help me with this problem ?

I have also tried === , == , single quote.

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
  • Isn't the `send` function asynchronous ? Does it accepts a callback function ? – Treycos Aug 22 '19 at 08:33
  • @Treycos ,I'm new to javascript . I actually don't know ? What should I do now ? – Maifee Ul Asad Aug 22 '19 at 08:35
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Aug 23 '19 at 03:36

1 Answers1

0

The onButtonClick function should be like this :

onButtonClick = () =>{
    if(this.state.email==='' || this.state.passwordHash==='')
        return;
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            if(String(request.responseText).match("true"))
            {
                console.log("Inside Match");
                window.location.href = '/home';
            }
        }
    };
    request.open('GET', 'http://localhost:8080/login/'+this.state.email+'/'+this.state.passwordHash, true);
    request.send();

};

So when it gets data in response, it will redirect to another page, or console log or whatever. But it should be done inside that async function onreadystatechange.

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86