1

I'm trying to write my first PHP script (hopefully). I want to send user input from a form inside an HTML page to a PHP script and validate them inside script. then, if there is any problem with input data, return to first page and highlight wrong fields. else go to another page (something like successful).

How do i send feedback from second script to first page without using forms?

9
  • 2
    Try using sessions. Commented Jun 7, 2011 at 19:01
  • Do you mean how will you redirect to the input form if inputs are not ok? Commented Jun 7, 2011 at 19:01
  • You can in your validation script add error variables (not the whole error message, just some code) to the original url and send user there, then get error messages using GET. Or you can in validation page add errors into a json and send json to the html page if it's not empty. Commented Jun 7, 2011 at 19:02
  • @Damien: yes. something like that. Commented Jun 7, 2011 at 19:03
  • why do you need feedback from the second script to the first page? as i understand the second script is only called after the validation took place. Which is the case in which it has to send info back to the first page? Commented Jun 7, 2011 at 19:04

4 Answers 4

3

In short, you'd have something like this:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   $errors = array();

   $name = $_POST['name'];
   if ($name !== 'Fred') {
      $errors[] = 'Please enter "Fred"';
   }

   ... validate more fields ...

   if (count($errors) == 0) {
     ... form is ok ...
     header('Location: everything_is_ok.php');
     exit();
   }
}

?>

<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
Enter 'Fred': <input type="text" name="name" value="<?php echo htmlspecialchars($name) ?>" /><br />
<input type="submit" />
</form>

Basically: Have the form page submit back to itself. If everything's ok, redirect the user to another page. Otherwise redisplay the form.

Sign up to request clarification or add additional context in comments.

Comments

2

Just make your Form POST to itself, then in your PHP check the values and if they are valid, don't display your form and do your submit code. If they are invalid, display the form with the values and errors displaying.

1 Comment

...and then, just evaluate validation script from another file? this is good idea! thanks.
2

Reload the first page and send the feedback in the session, for example. If session['errors'] exist, echo them. Note you'll have to include some php tags in your html page anyway.

Comments

0

Use a session... here's a link to help you get started: http://www.tizag.com/phpT/phpsessions.php

Comments

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.