Starting with an existing APIs using pure JavaScript

I need to build a login page where users can login with their username and password and get a token to stay connected. I have another file that does the authentication all by itself just by calling the connect function with username & password then if that user exists, we will get the token and “success” from the server otherwise we will get “reject” from server. I need to use pure javascript to call APIs and build the login page. I am lost and don’t know where to start, any suggestions? thanks in advance and please let me know if my question is not clear.

At its core the login page is not different from any other generic form:

  • you wait for the user to fill the input
  • you send the values to an endpoint
  • [optional] you do something in the interface with the response that the endpoint returns (for example a general validation).
<form onsubmit="myFunction(event)">
 <input type="text" placeholder="username" id="login_username" />
 <input type="password" placeholder="password" id="login_password" />
</form>
myFunction(event) {
// passing the event in case you want to prevent the default behaviour
event.preventDefault();

// now you can select values from the form and submit it to your API
var user = document.getElementById('login_username').value

// calling your login API - this example I assume is a Promise 
myAwesomeLoginAPI(user)
 .then(function(response) {
   console.log(response);
 })

}

Obviously this is a very generic example, you should tweak it to your needs.
Hope this helps you get started :slight_smile:

Thank you, That’s indeed clear and helpful but, I am beginner with APIs and AJAX requests. Is there a place or tutorial where I can get comfortable with APIs? Thanks again

This is probably a good place to start reading, I hope that whoever wrote this library/pice of code left a README guide on how to interact with it.

There is not a “unique” way to interact with an API, but each one has its own specification according to how they were built :slight_smile:

Thank you Marmiz, you are very kind and helping. I’ll go through their API Documentation but, again I think I am not that confident with AJAX to send the requests and deal with responses back in JSON so, if you any recommendations on where to get a good tutorial about that, I prefer video tutorials to books. Thanks again :slight_smile:

I don’t have any tutorial or resource on that topic, I’m sorry :frowning:

However I have a library that I often use when performing requests, it’s called axios.

So if you are able to pull it in in your project performing a POST request will be as simple as:

axios.post('yourAPIendpoint', {
    username: xxx,
    password: xxx
  })
  .then(function (response) { // the response from the server
    console.log(response);
  })
  .catch(function (error) { // in case we get some errors
    console.log(error);
  });

Good luck with your project :slight_smile:

Thank you Marmiz, I used the first way by calling a function and it worked well for me. Thank you again.

Now: I have another question: the same button in my form that use to submit, I named it 'Connect’
the moment I am connected I need to change the caption(text) of that button to ‘Disconnect’. I did that as well but, I need to use the same button to call another function to sign out (disconnect) but, when I click on that button, it calls the function to connect or submit the form again and call the sign in function. Is there a way to change that button to call sign out function instead of sign in while I am already signed in and I have a token? Thanks in advance, looking forward to hear your helpful advices.

There are multiple ways of accomplish that:

  • you can have two buttons, and hide/show one at a time
  • or you could have a unique one that changes its text on each click.

In my example I choose to have an ID (easier to grab imho in JS) and a unique handler. On click I perform a different logic based on the current ID of that button:

/* html */
<button id="connect" onclick="handleClick(event)">Connect</button>

/* js */
function handleClick(event) {
  event.preventDefault() // in case you want to prevent def behaviour
  const currentId = event.target.id;
  const buttonInstance = document.getElementById(currentId);
  
  if (currentId === 'connect') {
    /* perform your connect logic */
    
    // before returning
    // change the button id and text
    buttonInstance.setAttribute('id', 'logout');
    buttonInstance.innerHTML = 'Log Out'
    
  }
  
  if (currentId === 'logout') {
    /* perform your logout logic */
    
    // again switch to connect
    buttonInstance.setAttribute('id', 'connect');
    buttonInstance.innerHTML = 'Connect';
  }
}

I’ve chosen a pretty verbose syntax to give you an example, it could be slimmed down.
EDIT: you can try this example here

Anyway I really feel this should not be an easy task since it plain basic JS, and probably a very common task; with some research I feel you could have done this yourself without asking for any external advice.

What I’m trying to say is, if you’re learning, try to push yourself a little further :slight_smile:
Happy coding :+1:

1 Like

Thank you Marnie, I get what you mean. You are really helping and I listen to your advice. Thanks again and next time I’ll make sure to ask you only about challenging task :). Thanks and I hope a long and happy life for you and people like you