Baba Kamdev
Baba Kamdev

Reputation: 43

How to display php form result in the html if php processing is not in the same page without using ajax?

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?

Upvotes: 1

Views: 1279

Answers (3)

Awa Melvine
Awa Melvine

Reputation: 4087

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.

Upvotes: 0

Awa Melvine
Awa Melvine

Reputation: 4087

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>

Upvotes: 1

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

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.';
  }
}

Upvotes: 0

Related Questions