1

Lets say i have this form in form.php file.

<form action="process.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>

process.php contains

<?php 
if(isset($_POST['message'])){
  $message = $_POST['message'];
  if(!empty($message)){
    echo 'Your message: '.$message;
  }else{
    echo 'Please enter some message.';
  }
}

Now if i want to display the output of process.php inside the form.php's span tag of class result i either need to use ajax, or session/cookie or file handling. Is there any other way?

3 Answers 3

1

You can simply place the code in the process.php file inside the forms span tag.

<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result">
<?php 
    if(isset($_POST['message']))
    {
        $message = $_POST['message'];
        if(!empty($message))
        {
            echo 'Your message: '.$message;
        }
        else
        {
            echo 'Please enter some message.';
        }
    }
?>
</span>
Sign up to request clarification or add additional context in comments.

1 Comment

My form and php processing should be in two different files
0

Try this. It will post the form values in same page

<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>

<?php 
if(isset($_POST['message'])){
  $message = $_POST['message'];
  if(!empty($message)){
    echo 'Your message: '.$message;
  }else{
    echo 'Please enter some message.';
  }
}

1 Comment

it makes the html and php processing in the same page, which i am not looking for
0

OK this is one way of doing it: In form.php,

<form action="process.php" method="POST">
    <input type="text" name="message">
    <input type="submit" value="Submit">
</form>

<?php
    $var = $_GET['text'];
    echo "<span class=\"result\"> $var </span>";
?>

Then in process.php do this:

<?php 
   if(isset($_POST['message'])){
    $message = $_POST['message'];
      if(!empty($message)){
         // echo 'Your message: '.$message;
         header("location: form.php?text=$message")
      }else{
        echo 'Please enter some message.';
      }
}
?>

There are a few drawbacks using this method:

  1. Variable $message is passed through the URL and so should not be too long as URLs have length limits
  2. Using $_GET[] makes message visible on the URL so passwords and other sensitive information should no be used as the message.

I hope this helps.

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.