0

I have a form which I use to perform login operations. It should do the following when clicked on the submit button.

  1. Connect with firebase using javascript and authenticate the user.
  2. Get the email of the of the current user.
  3. submit the email to a servlet via POST, just like how submit works when you clicked on submit button.

Below is the code

function toggleSignIn() 
            {
                if (firebase.auth().currentUser) 
                {
                    // [START signout]
                    window.location.href = 'LoadSellPendingApprovals'
                    //firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        window.location.href = 'LoadSellPendingApprovals'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });

                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }

The form

 <form id="login-form" class="form" action="" method="post">
                                    <div class="form-group">
                                        <input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
                                    </div>
                                    <div class="form-group">
                                        <input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
                                        <i id="open" class="fa fa-eye fa-2x"></i>
                                        <i id="closed" class="fa fa-eye-slash fa-2x"></i>
                                    </div>
                                    <div class="form-group">
                                        <input type="submit" id="quickstart-sign-in" name="quickstart-sign-in" class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
                                    </div>
                                    <div class="form-group text-center forgot">
                                        <a href="#">Forgot username</a> / <a href="#">password?</a>
                                    </div>
                                </form>

I can get authenticate the user via firebase, get the email of current user, but I can't submit the email to another servlet via POST. How can I do this?

Update 1

I updated my function according to @naga - elixir - jar. Below is the code

function toggleSignIn() 
{
    if (firebase.auth().currentUser) 
    {
                    // [START signout]
                    //window.location.href = 'LoadSellPendingApprovals'
                    firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        // console.log(email) contains email
                        const options = {
                            method: 'POST',
                            headers: {
                                // set appropriate headers, assuming json here
                                //"Content-Type": "application/json",
                                 "Content-Type": "application/x-www-form-urlencoded"
                            },
                            // form body, assuming json
                            //body: JSON.stringify(email)
                             body: `email=${email}` <-- x-www-form-urlencoded form
                        }
                        alert(email);
                        // url = your url
                        fetch(url, options)
                            .then(response => response.json())
                            .then(data => console.log(data))
      .                     catch(e => console.error(e))
                            window.location.href = 'LoadSellPendingApprovals'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });
                alert('hi');
                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }

Now I get the following error

ReferenceError: url is not defined
    at (index):69
    at e.g (promise.js:829)
    at Dt (promise.js:1168)
    at Rt (promise.js:1142)
    at pt.t.Yb (promise.js:1113)
    at dt (run.js:132)

For anyone interested in full answer, please see the below function

function toggleSignIn() 
{
    if (firebase.auth().currentUser) 
    {
                    // [START signout]
                    //window.location.href = 'LoadSellPendingApprovals'
                    alert('existing user');
                    firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        // console.log(email) contains email
                        const options = {
                            method: 'POST',
                            url: 'LoginValidator',
                            headers: {
                                // set appropriate headers, assuming json here
                                //"Content-Type": "application/json",
                                 "Content-Type": "application/x-www-form-urlencoded"
                            },
                            // form body, assuming json
                            //body: JSON.stringify(email)
                             body: `email=${email}`
                        }
                        alert(email);
                         url = 'LoginValidator'
                        fetch(url, options)
                            .then(response => response.json())
                            .then(data => console.log(data))
      .                     catch(e => console.error(e))
                            window.location.href = 'LoginValidator'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });
                alert('hi');
                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }
Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
PeakGen
  • 18,056
  • 71
  • 208
  • 385
  • 1
    after you've retrieved email, send `POST` request through `AJAX` or `fetch API` etc. – 1565986223 Apr 14 '19 at 11:32
  • @naga-elixir-jar Thanks. I'm coming from Java background, no clear idea on Javascript. So can you show me how to do what you suggested? – PeakGen Apr 14 '19 at 11:37

2 Answers2

1

You can do it like:

After retrieving data in your code below, send fetch POST:

firebase.auth().signInWithEmailAndPassword(email, password)
  .then(function(firebaseUser) {
    var email = firebase.auth().currentUser.email;
    // console.log(email) contains email
    const options = {
      method: 'POST',
      headers: {
        // set appropriate headers, assuming json here
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded"
      },
      // form body, assuming json
      body: JSON.stringify({ email })
      // body: `email=${email}` <-- x-www-form-urlencoded form
    }
    alert(email);
    // url = your url
    fetch(url, options)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(e => console.error(e))
    window.location.href = 'LoadSellPendingApprovals'
})

More about fetch API

1565986223
  • 5,222
  • 2
  • 10
  • 27
0

You can POST form data to any server using a simple AJAX call. Please see the following links for further information on how to POST data using AJAX.

Any other questions please let me know.

Slyper
  • 726
  • 1
  • 11
  • 25