0

I've done this before where if a field isn't filled out the PHP validation "echos" an error like this:

if(empty($_POST['formfield'])) {
echo "Error";
die();
} else {
    ...
}

then triggered a msg with jquery validation like this (this is pseudocode):

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

I have recently had to set up some pages with a simple log in for a vendor to download files. Again, this is simple!

<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
?>
<!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
}
?>

so my issue is this
I can't seem to figure out how to echo a message that will then trigger an error message on the form as I have done in the first 2 code blocks.

Obviously

<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
**echo "Error";**
?>

just prints "Error" on page load. I need to figure out a way to simulate data being returned from the server - this form submits to itself - and show appropriate message (Username and/or Password are incorrect") if someone logs in with an incorrect username or password. I apologize for this being so long, and I truncated all the js stuff as I know it works. Thanks!

1 Answer 1

2

PHP is processed before Javascript. This gives you the ability to have PHP write out the Javascript that you want to display. Something like this should do what you want:

if ($_POST['username'] != $username || $_POST['password'] != $password) {
?>
<script>
$(document).ready(function() {

    $("#Error").html('ERROR MSG HERE').show();

});
</script>
<?php } ?>
Sign up to request clarification or add additional context in comments.

3 Comments

Just as a note: Make sure you put this in the HEAD or BODY tag.
@Cfreak - I'll give that a shot thanks! It will take some trial and error to integrate it with the other validation stuff. I'll see what I can come up with and post in pastebin. Thanks man
@Cfreak and cwalenpoole - I must be missing something. My PHP "validation" is above the doctype - If I output the JS with PHP in the body or head - how do I tie it into the condition that $username and or $password were incorrect?

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.