web-stars web-stars - 22 days ago 8
Javascript Question

javascript ajax login form handling

Im working on an ajax form to show errors without reloading the page. So if everything is good, then the user we be rediricted to

home.php
. But now the user will be also rediricted when there is an error.

I have tried for a while, I am a beginner when it comes to javascript/ajax/jquery. Can someone help me to find a why that the error will be displayed when neccesary?

This is my code so far:

index.php:

<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>


login.php

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>

Answer Source

Throw a 401 error if it fails login, this will stop the redirect.

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!$user->logUser($$_POST['username'], $_POST['password'])) {
        echo 'ok';
    } else {
        header("HTTP/1.1 401 Unauthorized");
        exit;
    }
}   
?>