0

I would like my server side PHP validation on a log in page to trigger an error in the client side jquery validation plug in validation. With non log in forms - structured to use a remote file as an action I just echo back a msg then trigger the client side validation error/success msg based on that returned value. I received some suggestions here before, but they did not work - some syntax errors (or my ignorance) here's some pseudocode:

<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
#would like to trigger the #errormsg here
?>
<!DOCTYPE>
<html>
<head></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" >
</body>
</html>
<?php
}
else {
?>
<!DOCTYPE>
<html>
<head></head>
<body>Logged in user sees this content</body>
</html>
<?php
}
?>

In my validation script the following:

//beginning
success: function(data) {
if (data=="Error") {
$("#Error").html('ERROR MSG HERE').show();
} else {
$("#Success").html('SUCCESS MSG HERE').show();
}
//rules, msgs etc

Currently if a user enters the wrong un/pwd it just resets the form, I'd like to tell them the info they entered was wrong. I know PHP can output JS - trying to just do something like in the PHP - but wherever I put that I get some syntax erros due to how the sections are broke up btwn the "} else {:

<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
<script>
   $(document).ready(function() {
      $("#Error").html('ERROR MSG HERE').show();
   });
</script>
?>

thanks!

2
  • where are you trying to echo out the JS? I don't see that part in your code above. Commented Sep 15, 2011 at 16:04
  • Edited the answer - I was just inserting the bottom part in the PHP where I have #would like to trigger the #errormsg here. If I try and insert and echo in the top part it just prints it on page load.thx Commented Sep 15, 2011 at 16:12

2 Answers 2

1

You just need to move your PHP output to the correct section. You can't put a <script> element into your HTML page before you even have a doctype or <html> tag. It has to go inside the <head> or <body> section.

<?php
$username = "foo";
$password = "bar";

if(!empty($_POST) && $_POST['username'] == $username && $_POST['password'] == $password) {

#display 'LOGGED IN' page here

} else {

   if(!empty($_POST) && ($_POST['username'] != $username || $_POST['password'] != $password)) {
    //Put the javascript error alert here
   }

  //Put the log in form here
}
Sign up to request clarification or add additional context in comments.

8 Comments

there must be something wrong with my setup - when I tried just adding an alert where you suggested - it loaded on page load. I need the JS function to only fire if the log in attempt is incorrect...
Did you check to see if the login attempt IS incorrect? you should do a print_r($_POST); and check the values. The fact that you got that alert suggests that the post value don't match the values you defined.
check it out, un foo pwd bar - bit.ly/ngvTnI i have the print in and it just prints it on page load...somehow i'm screwing this up!
If I enter the correct user name and password, I get logged in as you would expect. Did you keep the JS alert in there for an incorrect login?
Oh ok, Very simple fix for this. Just change your first if block to this. if(!empty($_POST) && ($_POST['username'] != $username || $_POST['password'] != $password)) { You were getting the alert on page load because when someone visit the first time, there is no $_POST['username']. as a result, the alert fires because NULL != $username.
|
0

I think you should go with Ajax Form Submission and server side data validation. This is the proper way to do it find example below.

HTML FILE

<html>
<head>
    <script type="text/javscript" src="latest-jquery.js"></script>
    <script type="text/javscript">

        $(function(){

            $('#login-form').submit(function(){

                $form = $(this);
                $message = $form.find('.message');

                $.post($form.attr('action'), $form.serialize(), function(data){

                    if( data.error ) {

                        $message.html( data.message ).removeClass('success').addClass('error');

                    } else if( data.success ) {

                        $message.html( data.message ).removeClass('error').addClass('success');

                    }

                }, 'json');

                return false;
            });

        });

    </script>
</head>
<body>
    <form id="login-form" action="PATH_TO_PHP_FILE" method="post">
        <div class="message"></div>
        <input type="text" name="username" />
        <input type="password" name="password" />
        <input type="submit" value="Login Now !" />
    </form>
</body>

PHP FILE

<?php
$username = 'foo';
$password = 'bar';

$response = array('error' => TRUE, 'message' => "Invalid Credentials");

if ( count($_POST['username']) && isset($_POST['username']) && isset($_POST['password']) && $_POST['username'] == $username && $_POST['password'] == $password  ) {

    $response = array('error' => FALSE, 'success' => TRUE, 'message' => "Bingo you have done it !");

}

print json_encode($response); //PHP function to convert array to JSON
exit; //To resolve IE Bug
?>

as per my knowledge this is the proper way.

1 Comment

great stuff! I do run AJAX form submission in other areas, this is just a simple log in no db checks etc..I'm trying to keep this simple and manageable, I just want to show the client their items once logged in from same page. I'll try and rework the thing using your suggestions, appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.