validate fields before submitting them in php - php

how can I validate the fields before submitting them to the other file and show error message in the same page like : *required fields
<?php
// Inialize session
session_start();
// Check, if user is already login, then jump to secured page
if (isset($_SESSION['username'])) {
header('Location: Pro_Lesson.php');
}
?>
<html>
<head>
<title>PHPMySimpleLogin 0.3</title>
</head>
<body>
<h3>User Login</h3>
<table border="0">
<form method="POST" action="log.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" name="password" size="20"></td></tr>
<tr><td> </td><td> </td><td><input type="submit" value="Login"></td></tr>
</form>
</table>
</body>
</html>

If you want to validate the fields before the form is submitted, you need to make use of javascript.
Take a look at this simple jquery plugin:
http://docs.jquery.com/Plugins/Validation
10 more jquery plugins here
One that does not use jquery

You can use sticky forms. For example, you have a session page (session.php) with a HTML form. If the user who wants to sign in doesn't write the correct user_name, you can display in the same page the error (action="session.php).

You should use Javascript to validate the form before sending it to the PHP page, and in the php page you validate it again.

Related

php passing data form

I use the GET method to pass data from index.php to profile.php
index.php code is
<html>
<body>
<form action="profile.php" method="GET">
username: <input type="text" username="user"><br>
password: <input type="password" name="pass"><br>
<input type="submit">
</form>
<button type="button" onclick="alert('task success')"/>click me"</button>
</body>
</html>
profile.php code is
<?php
echo " username: "$_GET ['username']."; password "$_GET['pass'];
?>
the output is
it es pass the inputs of the form successfully but I need it to appear in profile.php file
how can I make the output appear in profile.php page?
any help please
The problem is that the page is redirected. You will need to send an AJAX request to the action that you want to execute. With jQuery you can prevent a form from submitting like this:
$('form').submit(function (evt) {
evt.preventDefault(); //prevents the default action
}
You will need to collect the parameters, send them via AJAX and handle the response.

Confused about creating a "login" form

So what I want to do it kind of like a login form, but rather than it being individual users, it's more of a password locked page.
Here's sort of what I have for php
<?php
$user = $_POST['user'];
if($user == "placeholder")
{
include("randomfile.html");
}
else
{
if(isset($_POST))
{?>
<form id="login" method="POST">
User <input type="text" name="user" id="userID"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?}
}
?>
and it's basically doing what I want it to do, but if you were to go back (like use the go back button in the browser) it doesn't get rid of that submitted text (in this case, it would be "placeholder").
Any suggestions of any other way to do this, maybe easier or more basic because I just started with php, and is it possible so that if you enter "placeholder" and submit it, then go back, it doesn't have the User field already filled out with what you previously submitted?
<form id="login" method="POST" autocomplete="off">
That work for all the form, I think is the easiest. Ref: form:autocomplete

HTML Button that saves and move to the next page

I have a small problem. I want to have a button in my html page that saves every data that is added in the textfields and also when I click it to move to the next page.
My code is the follow...
<input type=button onClick="location.href='education.php'" value='Next'>
but it only moves to next page it does not save the data in the database ...
Can you help me please?
Thanks.
Remove the JavaScript
Change the type to submit
Wrap it in a <form>
Set the action of the form to education.php
Set the method of the form to post
Then, in education.php, read the data from $_POST and use PDO (with bound variables) to insert it into the database.
Try this :
<?php
if(isset($_POST['submit']))
{
// Insert Query Put here
header('Location: education.php');
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="Next" name="submit">
</form>
</body>
</html>
education.php :
<?php
echo "Successfully Updated.";
?>
You will have to set an action to your form like below because you are not submitting the form, but just redirection to another page without taking the form data.
<form action="education.php" method="post">
<!-- All your input fields here -->
<input type="submit" name="submit" value="Next">
</form>
and your education.php should be look like this:
<?php
//Get all parameters using $_POST
//Make A connection to database
//Choose a database in which you have to save the data
//Create a SQL query
// run query using mysql_query($query);
//Redirect to anywhere with header("Location:page.php");
?>

PHP form - on submit stay on same page

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)

Refresh page after form submitting

I have a little problem. I want to reload my page after submitting a form.
<form method="post" action="">
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input type="submit" value=" Update " id="update_button" class="update_button"/>
</form>
only use
echo "<meta http-equiv='refresh' content='0'>";
right after insert query before }
example
if(isset($_POST['submit']))
{
SQL QUERY----
echo "<meta http-equiv='refresh' content='0'>";
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
If you want the form to be submitted on the same page then remove the action from the form attributes.
<form method="POST" name="myform">
<!-- Your HTML code Here -->
</form>
However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header
function page_redirect($location)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
// I want the page to go to google.
// page_redirect("http://www.google.com")
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
action attribute in <form method="post" action="action="""> should be just action=""
You want a form that self submits? Then you just leave the "action" parameter blank.
like:
<form method="post" action="" />
If you want to process the form with this page, then make sure that you have some mechanism in the form or session data to test whether it was properly submitted and to ensure you're not trying to process the empty form.
You might want another mechanism to decide if the form was filled out and submitted but is invalid. I usually use a hidden input field that matches a session variable to decide whether the user has clicked submit or just loaded the page for the first time. By giving a unique value each time and setting the session data to the same value, you can also avoid duplicate submissions if the user clicks submit twice.
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.

Categories