JavaScript   

Pure JavaScript Ajax Call

Below is sample form code to demonstrate the pure JavaScript ajax call.

  <form id="login" action="checkLogin.php" method="post">
    <input class="field-val" type="text" id="username" name="username" placeholder="Username" required>
    <input class="field-val" type="password" id="password" name="password" placeholder="Password" required>
    <button type="submit" name="checklogin" onClick="checkLogin(); return false;">Login</button>
  </form>

Pure JavaScript ajax call code snippet

function checkLogin(){
  var fieldVal = document.getElementsByClassName("field-val");
    var formContents = new FormData(); 
    for(var i=0; i<fieldVal.length; i++)
    {
        formContents.append(fieldVal[i].name, fieldVal[i].value);
    }
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
              if(xmlHttp.responseText.trim()=='success'){
                  window.location = '/app/dashboard';
              }
              else{
                alert(xmlHttp.responseText);
              }
            }
        }
        xmlHttp.open("post", "checkLogin.php"); 
        xmlHttp.send(formContents); 
}

How to get and return values in the checkLogin.php

<?php
$username = $_POST['username'];
$password = $_POST['password'];
$login= false;
/*-- username and password matching logic starts --*/
$login= true;
/*-- username and password matching logic ends --*/
if ($login==true) { 
    echo "success"; 
} 
else
echo "Any Error Message will go here";
?>
Need Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us