Search code examples
phpfunctionauthenticationcall

Login Form with PHP without refreshing


I have a login form, which I validate via PHP. The problem is, that the action of the form is referencing to the file itself, so that it's gonna refreshing the page. I don't like this. Is it possible to check the inputs via PHP without refreshing the page?

Here's my code:

<?php
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     session_start();

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

     $hostname = $_SERVER['HTTP_HOST'];
     $path = dirname($_SERVER['PHP_SELF']);

     // Benutzername und Passwort werden überprüft
     if ($username == 'admin' && $passwort == 'admin') {
        $_SESSION['angemeldet'] = true;

            // Weiterleitung zur geschützten Startseite
            if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {
                if (php_sapi_name() == 'cgi') {
                    header('Status: 303 See Other');
                }
                else {
                    header('HTTP/1.1 303 See Other');
                }
            }

       header('downloadbereich.php');
       exit;
       }
      }
?>

<link href="login.css" rel="stylesheet" type="text/css" />
<div class="contactForm" id="contactForm" style="width: 500px; margin: auto; float: left;">


<form name="myform" method="post" action="login.php<!-- this is what I want to remove-->">
    <p class="form" style="width: 245px; height: 116px; margin-right: 10px;"><input class="field" type="text" name="username" placeholder="Name" />
    <input class="field" type="password" autofocus name="passwort" placeholder="Passwort" />
    <button class="button" name="Submit">Login</button></p>

</form>
</div>

Solution

  • With jQuery - AJAX:

    $.post('login.php', {
        username : $('input[name=username]').val(),
        password : $('input[name=password]').val()
    });