What would be the best way to display a success message after submitting a form and then redirecting.
I'm developing a script with smarty template engine and i don't want to use javascript as i want it to be as easy as possible for a user to design his or her own template and i have tried using sessions to display the message it seems to unset after redirecting for example
The Form
<form action="" id="comment_form" method="POST">
<input type="hidden" name="movie_id" id="page_id" value="{$mov.mid}" />
<input type="hidden" name="user_id" id="user_id" value="{$logged_id}" />
<input class="span2" name="comment" type="text" />
<button class="btn" name="add_comment" type="submit">Add Comment</button>
</form>
PHP
if (isset($_POST['add_comment'])) {
if (!empty($_POST['comment'])) {
$user_id = $logged_id;
$post_comment = mysqli_real_escape_string($con, $_POST['comment']);
$movie->AddMovieComments($con, $movie_id, $user_id, $post_comment);
$_SESSION['insert'] = 'success';
header ('Location: '.$_SERVER['REQUEST_URI']);
} else {
$_SESSION['insert'] = 'empty';
}
}
Now trying to display the success in tpl
{if isset($smarty.session.insert)}
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Success</h4>
Your Comment was successfully added
</div>
{/if}
{php}unset($_SESSION['insert']);{/php}
So can anyone help me out and tell me the best way to do this or tell me why it is unset before it is displayed.
Try
if( isset($_SESSION['insert']) && $_SESSION['insert'] == 'success')
{
//Your alert
unset($_SESSION['insert']);
}
I don't think a SESSION variable is the best way to do this.
In our template, have a simple condition check to see if a Smarty variable exists:
{if $success}Your comment was added{/if}
Then, in your PHP that handles the transaction, simple initiate the variable, set it to true or false depending on the outcome, and assign it in Smarty before your template is displayed
$success = false;
if (!empty($_POST['comment'])) {
$success = true;
}
$smarty->assign("success",$success);
$smarty->display("template.tpl");
Of course, should verify that the insert was successful before you make $success = true, but you get the drift.
Related
I'm trying to build a sign up script with PHP for a website, however whenever I input information into one of the "input" tags, for some reason they're being returned as empty, although they really aren't.
In my signup.php I have created this form to post data:
<form class="form-inline" action="includes/signup-inc.php" method="post">
<div class="">
<input type="text" name="email" class="form-control transparent" placeholder="Your email here...">
<input type="password" name="pwd" class="form-control transparent" placeholder="Your password here...">
<input type="text" name="uid" class="form-control transparent" placeholder="Your username here...">
<button type="submit" name="submit" class="btn btn-danger btn-fill">Sign Up</button>
</div>
</form>
Which brings the data over to my signup-inc.php file to allow a user to signup for an account. Whenever I try to signup for an account on my website, the error I created called "emptyInputSignup" keeps being thrown back.
This is what I have in my signup-inc.php:
if(isset($_POST["submit"])){
$email = $_POST["email"];
$pwd = $_POST["pwd"];
$uid = $_POST["uid"];
require_once 'dbh-inc.php';
require_once 'functions-inc.php';
if(emptyInputSignup($email, $pwd, $uid) !== false){
header("location: ../signup.php?error=emptyinput");
exit();
}
And the function being referenced, which I have created in my 'functions-inc.php' is here:
<?php
function emptyInputSignup($email, $pwd, $uid){
$results;
if(empty($email) || empty($pwd) || empty($uid)){
$results = true;
}
else {
$results = false;
}
}
Personally what I've done to try to debug to see if any data is in fact coming through is nulled the error handle which brings you back a page, to signup.php and instead echo'd a statement into the signup-inc.php page with the data being input. All 3 variables are echoed to the signup-inc.php page with the exact string written in the input field.
Any ideas on what I could be missing?
I'm not sure if this is it, but I don't see you actually return the result from the helper function. I think you can simplify it a bit as well, maybe give this a try
<?php
function emptyInputSignup($email, $pwd, $uid){
return empty($email) || empty($pwd) || empty($uid);
}
This is my login form:
<div class="form-container">
<h1 style="text-align:left">Login Here!</h1><br>
<form class="form-horizontal" action="<?php echo base_url(); ?>index.php/User_Authentication_Controller/login_user" method="POST">
<div class="error_msg1"></div>
<input autofocus="autofocus" type="text" name="txt_login_username" class="form-control" placeholder="Username.."/><div class="error_msg2"></div>
<input type="password" name="txt_login_password" class="form-control" placeholder="Password.." /><div class="error_msg3"></div>
<center><button class="btn btn-info" type="submit">Login</button><br/><br/>
Forgot Password?</center>
</form>
</div>
This is my controller:
public function login_user(){
$username = $this->input->post('txt_login_username');
$password = md5($this->input->post('txt_login_password'));
$result=$this->LogIn_Model->login($username,$password);
if (!empty($username) && !empty($password)) {
if($result!=null){
$_SESSION["username"] = $username;
$_SESSION["id"] = $result["0"]["Account_no"];
$_SESSION["Usertype"] = $result["0"]["Usertype"];
if($result["0"]["Status"] == 1){
if($result["0"]["Usertype"] == 0){
redirect('User_Authentication_Controller');
}
else if($result["0"]["Usertype"] == 1){
redirect('Pages_Controller/show_adminpage/');
}
}
else if($result["0"]["Status"] == 0){
redirect('User_Authentication_Controller');
}
}
else{
redirect('User_Authentication_Controller');
}
}
else{
redirect('User_Authentication_Controller');
}
}
This actually works!
Now my question is:
As you see in the else if($result["0"]["Status"] == 0){}, all I want is that after I submitted the page it will redirect back to the login, and I want that the
<div class="error_msg1"></div>
will show an error telling, "Your account has been deactivated by the Admin" And if he inputs a username it will stay still as he submit it! how will I do that? If he inputs Username: Michael and Inputs a wrong password, I want the Username: Michael to stay still! How will I do that after the form submit?
you can use set_userdata to store error msg and can show:
in your controller:
else if($result["0"]["Status"] == 0){
$this->session->set_flashdata('error_msg1','Some Error Msg!');
}
and in your view:
<?php if($this->session->flashdata('error_msg1')) : ?>
<div class="alert alert-success">
<span class="alert-rr">
<i class="fa fa-check-circle" aria-hidden="true"></i>
</span>
<span class="alert-msg">
<?php echo $this->session->flashdata('error_msg1'); ?>
</span>
</div>
<?php endif; ?>
Way 1
Use AJAX instead of form. Your js make an ajax post to your server, and then get the result. Depending on it, your js reacts, for example, showing error messages. This is a good choice.
Way 2
For example, you can set $_SESSION['ShowErrorMsg1']=true in login_user, then in your login page php, just say:
.
if(isset($_SESSION['ShowErrorMsg1']) && $_SESSION['ShowErrorMsg1']==true){
echo '<div class="error_msg1"></div>';
}
then the error msg will be shown.
UPDATE:
The main idea is that you can storage anything you want to pass it from one php to another php in $_SESSION. If you want to pass on $msg_content for example, just use $_SESSION['somekey']=$msg_content; in one php. Then in another php use $_SESSION['somekey'] who storages the data of $msg_content.
How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}
I have had this issue intermittently for some time, but I only just had it happen repeatedly enough to actually trouble shoot it. It happened repeatedly in FF but I have seen it in Chrome as well.
I have login form as below, it is very simple, email address and password and a submit button
<form method="post" action="login.php" id="valid" class="mainForm">
<fieldset>
<div class="">
<label for="req1">Email:</label>
<div class="loginInput"><input style="width: 100%;" type="text" name="email" class="validate" id="req1" /></div>
<div class="fix"></div>
</div>
<div class="">
<label for="req2">Password:</label>
<div class="loginInput"><input style="width: 100%;" type="password" name="password" class="validate" id="req2" /></div>
<div class="fix"></div>
</div>
<input name="action" type="hidden" value="log_in" />
<div class="">
<div class=""><input type="checkbox" id="check2" name="remember_me" value="1"/><label>Remember me</label></div>
<input type="submit" value="Log me in" class="submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
Submitting the above form wouldn't log me in, it just displayed the login form again as if nothing was submitted. So I amended the login.php file that is submitted to, and at the very top added print_r($_POST);
When I submitted the form again all it displayed was an empty array. It was like the form variables just weren't being sent. I tried several accounts, and got a blank array each time.
I then tried to enter an email address that I new wasn't in the database, and to my amazement the $_POST array populated with the fake email and password. I then tried a real account again and it was blank.
The last thing I did was to deleted the session cookie in FF for the site, and then try again. To my surprise I could then log in OK. I logged in and out a few times after that with no problem at all!
So my question is: What was that session cookie doing to prevent the post variables from being sent (if that was what was actually happening) and why did it populate the $_POST array if I entered a fake email address? The print_r($_POST) I did was the very first thing in the script, before any other processing or includes, yet it still was empty??
I guess I don't really know how browsers deal with session cookies, but this behaviour has me completely clueless.
Any advice on how to troubleshoot this, or general session advice.
EDIT - PHP Code for the login.php
<?php
print_r($_POST);
include '../inc/init.php';
$action = fRequest::get('action');
if ('log_out' == $action) {
fSession::destroy();
fAuthorization::destroyUserInfo();
fMessaging::create('success', '<center>You were successfully logged out</center>');
}
if (fAuthorization::checkAuthLevel('user') || fAuthorization::checkAuthLevel('buser')) {
fURL::redirect('index.php');
}
if ('log_in' == $action) {
# Set session variables etc...
}
The init.php include at the top sets the database connetion strings and starts the session etc... I am using FlourishLib Un-Framework set of classes which includes a session class.
Thanks
try this code please
$actions = array('log_in', 'log_out');
$action = fRequest::getValid('action', $actions);
if ($action == 'log_out') {
fSession::clear();
fAuthorization::destroyUserInfo();
fMessaging::create('success', URL_ROOT . 'index.php', 'You were successfully logged out');
fURL::redirect(URL_ROOT . 'index.php');
}
if ($action == 'log_in') {
if (fRequest::isPost()) {
try {
$valid_login = fRequest::get('username') == 'yourlogin';
$valid_pass = md5(fRequest::get('password')) == 'md5(youpassword)';
if (!$valid_login || !$valid_pass) {
throw new fValidationException('The login or password entered is invalid');
}
fAuthorization::setUserToken(fRequest::get('username'));
fURL::redirect(fAuthorization::getRequestedURL(TRUE, URL_ROOT . 'index.php'));
} catch (fExpectedException $e) {
fMessaging::create('error', fURL::get(), $e->getMessage());
}
}
include VIEWS_DIR . DS . basename(__FILE__);
}
I have two input fields and whenever I open my page, it displays errors since at the start user has not entered any input to any of the field (& the errors are displayed because the user input is used in sql queries to retrieve data).
I just want to display those two forms at start of the page not the errors.
Both inputs are required to execute the Compare button. If user has not entered either one of the inputs it should not send request to php for scripting.
I mean the Compare button should send request only if both inputs are filled otherwise it should give a message to user to Type the required fields.
How to do this?
$trimUser= trim ($_POST['name']);
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
& here is my form:
<form action="index.php" method="POST">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
You have to use java script or jQuery for validate both fields are not empty. For Example..
<form action="index.php" method="POST" onsubmit="return validate()">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/>
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
</form>
<script type="text/javascript">
function validate(){
var field1 = document.getElementById('field').value;
var field2 = document.getElementById('field2').value;
if(field1 != '' && field2 != '' ){
return true;
} else{
alert('Type the required fields');
return false;
}
}
</script>
Here if Both fields are not empty then it will be allow to submit form. And In PHP script Add
if(isset($_POST) && !empty($_POST)){
//code comes here
}
I hope it will be helpful for you.
thanks
You can add a check to verify if the request is a post request :
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Place your error checking code here
}
Ehs4n is right, but I would be more specific and do something like :
if(!empty($_POST['compare'])) {
#validation
}
Your button code would have to be changed to :
<button name="compare" value="1" class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
There are two reasons I would do this:
Using !empty() makes sure you don't get an error when $_POST['compare'] is empty
Checking $_POST['compare'] instead of just $_POST makes sure errors are only shown if someone clicks the button.
This last point is key because if you have multiple forms on the page or you happen to set a $_POST variable elsewhere you would still be showing errors.
Use the if condition with isset($_POST) before loading the post.i.e.,
if (isset($_POST)) {
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
I simply got rid all of all the errors by adding this error_reporting(E_ERROR | E_PARSE); at the start of my code.
However if anyone want to check display validation error messages , one can do easily by what others have mentioned . i.e By using if($_Post).
Anyway ,Thank you everyone for the help.
Add if clause like
if($_POST) {
...your validation code
}
Think of redirecting people AFTER the error to the same page they were:
echo '<script>location.href=\'example.php\'</script>';