I want to display messages at top ids "MessageError" and "MessageOK" according to POST results. Example:
<p id="MessageError"></p>
<p id="MessageOK"></p>
<form name="Form" method="post" action="<?php $_SERVER[ 'PHP_SELF' ]; ?>" enctype="multipart/form-data" accept-charset="UTF-8" id="Form">
<input type="text" name="test" value="" /> <input type="submit" name="Submit" value="" />
</form>
<?php
if ( isset ( $POST[ 'Submit' ] ) ) {
if ( $_POST[ 'test' ] ) {
// Echo message at "MessageOK
}
else {
// "Echo message at "MessageError"
}
}
?>
Any help will be appreciated.
Thank you.
Move the code above your form to print the error message above your form. Also your paragraph tags can be created on the fly, to avoid waste:
<?php
if(isset($_POST['submit'])){
if($_POST['test'])echo("<p id='MessageOk'>There was an Error</p>");
else echo("<p id='MessageError'>There was no error</p>");
}
?>
If you are dead set on adding content to pre-created divs using PHP, can I suggest creating an input using PHP eg:
<?php
$test = $_POST['test'];
echo("<input type='hidden' id='test' value='$test' />");
?>
And then using JavaScript to append data:
if(document.getElementById('test').value){
document.getElementById('MessageOk').innerHTML = 'No Error';
}
else{
document.getElementById('MessageError').innerHTML = 'Error ??';
}
move your php code over the form, assign the echo message to a variable and use <?php echo $variable; ?> to print the message at the appropriate place...
Make sure you include the _ on your post variable.
$_POST[]
Related
Simple php code to post a value and echo it inside if(isset()), when click on submit button, but it's not working.
<?php
if(isset($_GET['q']))
{
$q=$_GET['q'];
//echo "thisss iss qqqq".$q; this is working
$_SESSION['q']=$q;
if($q=="1")
{
?>
<form action='#'>
<tr>
<input type='text' name='txt_code' >
<input type='submit' name='code_sub' value='Showcd'>
</tr>
</form>
<?php
}
//here I wrote code for to echo $bkCode when click on 'showcd' button but it's not working
<?php
if (isset($_POST["code_sub"]))
{
echo $bkCode=$_POST['txt_code']; // THIS IS NOT WORKING
}
}
?>
It doesn't even enter inside the if (isset($_POST["code_sub"])) part
Default action of a form is GET. You have to specify that u want to do a POST :
<form action="#" method="POST">
A first, you should set the var, and after that a simple output:
<?php
if (isset($_POST["code_sub"]))
{
$bkCode=$_POST['txt_code']; // THIS IS WORKING
echo $bkCode;
}
?>
Also you need to set the form method to "POST"!
<form action='the_link' method="POST">
For using the post method
<form action='the_link' method="POST">
This will help ..:)
if($media=="pet")
{
if($pressure=="bar")
{
if($f_req=="ltr/m")
{
$kvreq=$flowreq/16.666666667*16.6667/(pow(($presur*1/0.98066/660*1000),0.5));
echo "<b>KV Required:- </b>$kvreq ";
?>
<br/><br/>
<?php
if($kvreq > 14 and $kvreq <= 38){
$minOrfice=10;
$n_kv=38;
$maxOrfice=7;
echo "<b>Minimum Orfice Required:- </b>$minOrfice";?>
</br></br>
<?php
$n_kv1=($n_kv/16.66667*(pow($presur*1/0.98066/660*1000,0.5)))*16.666666667;
echo "$n_kv1 <b>liter/min</b>";?>
</br></br>
<?php
echo "The Max Flow at $maxOrfice orfice";?>
</br></br>
<?php
$maxfo=((14/16.66667)*(pow(($presur*1/0.98066/660)*1000,0.5)))*16.666666667;
echo "$maxfo <b>liter/min</b>";?>
<form method="get" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input name="chkb1" type="checkbox" />
<input type="submit" value="Submit" name="chk_btn" id="chk_btn"/>
</form>
<?php
if(isset($_POST['chk_btn'])){
echo "$abc";
}
}
}
}
}
...................................................................................................................................................................................
your form method is GET while you're attemptig to get POST data
change this:
if(isset($_GET['chk_btn']))
if(isset($_POST['chk_btn'])) to if(isset($_GET['chk_btn'])) should fix the problem but OP refuse that still cannot display any text.
I suspect that upon submitting the the form again in the page it lose the value of $media, $pressure and so on there it never pass the if statements and never proceed on next process
if($media=="pet")
{
if($pressure=="bar")
{
if($f_req=="ltr/m")
{
I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
I am generating form and handling the submit event in the same file.
If user has not entered the title, I want to display the form again and include an error message (e.g. "You forgot the title.").
That means that I have to duplicate code twice - once to diplay empty form and second to display form with body and ask user to enter title:
<?php if(strlen(strip_tags($_POST['posttitle'])) == 0):
// Display the form with question body that user has entered so far and ask user to enter title.
?>
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
<?php endif;?>
<?php elseif ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action']) && $_POST['action'] == 'post') : ?>
<!-- Everything ok - insert post to DB -->
<?php else :
// just display form here (again ouch!)
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
?>
I would do it like this:
If REQUEST_METHOD is POST I will validate the input and collect messages in an array ($errors in my code).
Then I would just print the form and if there was an error the code will print it.
<?php
$errors = array();
function print_value_for($attr) {
if (isset($_POST[$attr]))
echo $_POST[$attr];
}
function print_error_for($attr) {
global $errors;
if (isset($errors[$attr]))
echo $errors[$attr];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do validation here and add messages to $errors
// like $errors['posttitle'] = "The title you entered is bad bad bad";
if (empty($errors)) {
// update database and redirect user
}
}
?>
<!-- display the form and print errors if needed -->
<form>
<?php print_error_for('posttitle'); ?>
<input name="posttitle" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postauthor'); ?>
<input name="postauthor" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postbody'); ?>
<textarea name="postbody">
<?php print_value_for('posttitle') ?>
</textarea>
<input type="submit">
</form>
PS. Consider using MVC to separate code and templates.
Here is a quick way to do that.
<form>
<input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>"/>
<input type="text" name="field_a" value="<?php echo $_REQUEST['field_a']; ?>"/>
....
</form>
But I can also advise you to display a var called $title which is the result of a check on $_REQUEST['title].
You could use an output buffer to grab the form and then assign it to a variable like so:
<?php
ob_start();
include('path/to/your/form');
$form = ob_get_flush();
// then later you can just go
print $form;
?>
Hope this helps
When you display the form, use the possibly empty $_POST values as default field values for both the title and question body. If either is empty, the form will display the second time with the other already filled in:
<?php
$message = "";
if (empty($_POST['title'])) $message .= " Please enter a title.";
if (empty($_POST['body'])) $message .= " Please enter a body.";
?>
<form action='me.php'>
<input name='title' type='text' value='<?php if (!empty($_POST['title'])) echo htmlentities($_POST['title'], ENT_QUOTES); ?>' />
<textarea name='body'><?php if (!empty($_POST['body'])) echo $_POST['body']; ?></textarea>
</form>
Read this MVC
Your can write form in view, handler in controller, and business logic in model
Here's what I have:
<html>
<head>
<?php
$validForm = false;
function getValue($field){
if(isset($_GET[$field])){
return $_GET[$field];
}
else{
return "";
}
}
function validateForm(){
//magic goes here.
}
?>
</head>
<body>
<?php if($validForm == false){ ?>
<form action="class2.php" method="get">
<dl>
<dt>First Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('name')) ?>" name="name" />
</dd>
<dt>Last Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('lastname')) ?>" name="lastname" />
</dd>
<br />
<dt>
<input type="submit" value="enviar" />
</dt>
</dl>
</form>
<?php
} else {
?>
<h1>Congratulations, you succesfully filled out the form!</h1>
<?php }
?>
</body>
Where would I put the validateForm() call? I'm not sure.
What I want is to continue showing the form until the $validForm variable is true. :)
Thank you SO you always help me out.
function validateForm(){
if ( ) // Your form conditions go here
{
return true;
} else {
return false;
}
}
if ( $_GET ) // Only validate the form if it was submitted
{
$validForm = validateForm();
} else {
$validForm = false;
}
Examples for some conditions:
if ( !empty ( $_GET[ 'name' ] ) and !empty ( $_GET[ 'lastname' ] ) ) // Check if the user entered something in both fields
I can only recommend you to change your getValue function too.
It would be a good idea to change
return $_GET[$field];
to something like
return htmlspecialchars ( trim ( $_GET[$field] ) );
This will remove unnecessary whitespace and escape the output at once.
The next or probably first step you should take would be to change your form from GET to POST as it is, in most cases, a bad idea to send form data via GET.
You have to add a name to your submit button :
<input type="submit" value="enviar" name="validate" />
And after the declaration of validateForm
you put
if(getValue("validate") != "")
validateForm();
I'd check for the $_POST-variables in your getValue-function as you're trying to validate form-data (your checking $_GET-variables which is data submitted through the URL), you also may want to add "trim"
give the submit-button an id and check if the form has beed submitted that way
e.g. <input type="submit" value="enviar" id="submitButton" />
setting $validForm would look this this: $validForm = validateForm(); (instead of "$validForm = false;")
your validateForm-function should then check whether "$_POST["submitButton"]" is set and if your data is valid (set, right type, etc. etc.), if all of that is ok, return "true", otherwise "false"
<html>
<head>
<?php
$validForm = validateForm();
C.