0

When a user fills a login form with an username and a password I use php to do a server-side validation of the data inputted by comparing it with the one in the "users" table in the SQL database. I'd like to notify the user if the password is incorrect without redirecting him - using a javascript dialog, for instance. Is that possible? The only way I found to notify the user was:

if ($password_given != $password_from_db) {
    echo "Wrong password."; // Dull non-html notification issued by the server
};

or

if ($password_given != $password_from_db) {
    header('Location: index.php?page=wrongpassword'); //Need redirection
};

Is there anyway to this differently?

A javascript to get the inputted data, send it to the server to be processed is an idea, but how could I return a result for the javascript to use?

Alex
  • 1,416
  • 4
  • 16
  • 42

3 Answers3

1

Can be done using AJAX -

<form onsubmit="return ajaxsubmit();">
...
</form>

Javascript-

function ajaxsubmit() {
    param = 'email=' + document.forms.login.email + '&' + 'pass=' + document.forms.login.pass;
    xhr = new XMLHttpRequest();
    xhr.open('POST', 'process.php', true);
    xhr.onload = function() {
        if(xhr.responseText.indexOf("Wrong")>=0) {
            //wrong password, ask user to try again
        } else {
            //correct password, redirect or do stuff.
        }
    };
    xhr.setRequestHeader('Content-type: application/x-www-form-urlencoded'); 
    xhr.send(param);
    return false;
}

You can keep your server-side validation code in process.php and use the above code in the page where the form is. You're done.

ShuklaSannidhya
  • 8,572
  • 9
  • 32
  • 45
1

JQuery

$.post("test.php", $("#testform").serialize())
.done(function(data) {
  if( data=='validated')
window.location.href = "successpage.php";
else
 alert ('password dont match!');

});

php

if ($password_given != $password_from_db) 
    echo "notvalidated."; 
else
   echo     echo "validated.";
Bhavin Rana
  • 1,554
  • 4
  • 20
  • 40
0

You can make an Ajax call to the server and allow the user to login OR display error message, based on the result returned by server.

jjk_charles
  • 1,250
  • 11
  • 23