DEV Community

Cover image for Vanilla XMLHttpRequest method without using jquery
Opuama Lucky
Opuama Lucky

Posted on

Vanilla XMLHttpRequest method without using jquery

Introduction

Ajax is short for "Asynchronous JavaScript and XML", it is a set of web development techniques that uses various web technologies on the client-side to create asynchronous web applications without interfering with the display and behaviour of the existing page.
Ajax is a mechanism for making partial page updates. It enables you to update sections of a page with data that comes from the server, whilst avoiding the need for a full refresh. Making partial updates in this way can be effective in creating fluid user experiences and can decrease the load put on the server.

Anatomy of a basic Ajax request:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'send-ajax-data.php');
xhr.onreadystate = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) {
      console.log(xhr.responseText); // 'This is the returned text.'
    } else {
      console.log('Error: ' + xhr.status); // An error occurred during the request.
    }
  }
};
xhr.send(null);
Enter fullscreen mode Exit fullscreen mode

Here, we are declearing a variable of the required class to make an HTTP request to the server. We are then calling its open method, specifying the HTTP request method as the first parameter and the URL of the page we’re requesting as the second.
The onreadystate is asynchronous, which means it gets called at any time. These types of functions are callbacks — one that gets called once some processing finishes.
Finally, we call its send method passing null as a parameter. If POST-ing the request, this parameter should contain any data we want to send with the request.
There are more detailed explanation
Lets start coding and see the outcome and beauty of vanilla js

  • Create a login form
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" csontent="width=device-width, initial-scale=1.0">
    <title>pratical login page</title>
    <link rel="stylesheet" href="fontawesome-free-5.15.4-web/css/all.css">
    <link rel="stylesheet" href="index.css">
</head>
<body>
   <div class="wrapper">
        <section class="form login">
            <header>Login</header>
            <form action="#" method="POST" enctype="multipart/form-data" id="myForm">
                <div class="error-txt"></div>
                    <div class="field input">
                        <label >Username</label>
                        <input type="text" name = "username" placeholder="Enter username">
                    </div>
                    <div class="field input">
                        <label >Password</label>
                        <input type="password" name ="password" placeholder="Enter your password">
                        <i class="fas fa-eye"></i>
                    </div>
                    <div class="field button">
                        <input type="submit" value="continue to chat" >
                </div>
            </form>
            <div class="link">Not yet signup? <a href="index.php">Signup now</a></div>
        </section>
   </div>
   <script src="login.js"></script>
Enter fullscreen mode Exit fullscreen mode
  • Style login page if neccesary

Lets add css (cascading stylesheet) to structure and beautify the page.

*{
    margin: 0 ;
    padding: 0 ;
    box-sizing: border-box;
    text-decoration: none;
    font-family: 'poppins',sans-serif;
}
body{ 
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #f7f7f7;
}
.wrapper{
background: rgb(172, 224, 87);
width: 450px;
border-radius: 16px;
box-shadow: 0,0,128px,0 rgba(0, 0, 0, 0.1),
            0 32px 64px -48px rgba(0, 0,0,0.5);
}
/* signup form css code */
.form{
    padding: 25px 30px;
}
.form header{
    font-size: 25px;
    font-weight: 600;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;
}
.form form{
    margin: 20px 0 ;
}
.form form .error-txt{
    color: #721c24;
    background: #f8d7da;
    padding: 8px 10px;
    text-align: center;
    border-radius: 5px;
    margin-bottom: 10px;
    border: 1px solid #f5c6cb;
    display: none;
}
.form form .field{
    position: relative;
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
}

    .form form .name-details{
display: flex;
}
form .name-details .field:first-child{
    margin-right: 10px;
}
form .name-details .field:last-child{
    margin-left: 10px;
}
.form form .field input{
    outline: none;
}
.form form .input input{
    height: 40px;
    width: 100%;
    font-size: 16px;
    padding: 0 10px;
    border: 1px solid #ccc;
}
.form form .image input{
    font-size: 17px;
}
.form form .button input{
    margin-top: 13px;
    height: 45px;
    border: none;
    font-size: 17px;
    font-weight: 400;
    background: #333;
    color: #fff;
    border-radius: 5px;
    cursor: pointer;
}

.form form .field i{
    position: absolute;
    right: 10px;
    color: #ccc;
    top: 58%;
    transform:(-50%);
    cursor: pointer;
}
.form form .field i.active::before{
    content: "\f070";
    color: #333;
}
.form .link{
    text-align: center;
    margin:10px 0;
    font-size: 17px;

}
.form .link a{
    color: #333;
}
.form .link a:hover{
    text-decoration: underline;
}
Enter fullscreen mode Exit fullscreen mode
  • Create connection to database
<?php
$conn = mysqli_connect("localhost","root","","a_database");
if ($conn) {

}else{
    echo "Not connected ";
}
?>
Enter fullscreen mode Exit fullscreen mode
  • Create a php file connecting to the database
<?php
include "connection.php";

    $username =   $_POST['username'];
    $password =   $_POST['password'];

    if (! empty($username) && ! empty($password)){
//lets check if user entered email and password matched database and table
      $sql = mysqli_query($conn, "SELECT * FROM users WHERE username = '$username' AND password = '$password '" );
      if (mysqli_num_rows($sql) > 0 ) {//check if user credential matched
       echo "success";

      }else {
        echo "Username and Password incorrect";
      }
    }else {
      echo "All field are required";
    }


?>
Enter fullscreen mode Exit fullscreen mode

In the above code we include the connection script and ensure the username and password is correct if not the page should echo the Else statements

  • Using the vanilla javascript to fetch data from the database
const form = document.querySelector("#myForm"),
  errorText = form.querySelector(".error-txt");

form.onsubmit = (e) => {
  e.preventDefault();//preventing form from submitting
  //start with ajax

  let xhr = new XMLHttpRequest();// creating xml object
  xhr.open("POST", "get.php", true);
  xhr.onload = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {//status 200 is a successful return.
        let data = xhr.response;

        if (data == "success") {

          location.href = "logout.php";

        } else {
          errorText.textContent = data;
          errorText.style.display = "block";

        }
      } 
    }
  }
  // sending form from ajax to php
  let formData = new FormData(form); // creating new form object.
  xhr.send(formData);//sending the  form data to php

}
Enter fullscreen mode Exit fullscreen mode

Here is the image of the login form

login form

Output after submitting the form
result

Conclusion

In this article we have been able to create a simple login page that accept a username and password and then send to the backend(Database) for authentication without loading the entire page using Vanilla Ajax.
I hope you’ve enjoyed bench press of vanilla Ajax. In fact, we’ve covered most of the basics of Ajax without the crutches, ahem shackles, of jQuery.

I’ll leave you with this concise way of making Ajax calls:

Top comments (0)