Stop on submit form refreshing page - php

I am having a problem, since my website reloads each time somemone submit a form.
It's a wide scroll, so i just found also another solution, but gives me an error.
PHP CODE:
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
$success='<h1>Thank you!</h1>';
unset($_SESSION['sent']);
header('Location: index.php#5');
}
?>
FORM CODE:
<form class="demo-form" name ="demo-form" data-parsley-validate method="post" action="submit.php" >
<ul>
<li class="js-hide-label">
<label for="name">Nombre:</label>
<input type="text" placeholder="Nombre" id="name" name="name" data-parsley-trigger="change" required tabindex="1" autocomplete="off" value="<?php echo (isset($_SESSION['post']['name']) ? $_SESSION['post']['name'] : ''); ?>" >
</li>
<li class="js-hide-label">
<label for="email">Your Email:</label>
<input type="email" placeholder="Your Email" id="email" data-parsley-trigger="change" name="email" autocomplete="off" required tabindex="2" value="<?php echo (isset($_SESSION['post']['email']) ? $_SESSION['post']['email'] : ''); ?>">
</li>
<li class="js-hide-label">
<label for="message">Message:</label>
<textarea placeholder="Message…" id="message" name="message" tabindex="3" required data-parsley-trigger="keyup" textarea id="message" data-parsley-minlength="20" data-parsley-maxlength="100" data-parsley-minlength-message = "Come on! You need to enter at least a 20 caracters long comment.." data-parsley-validation-threshold="10"><?php echo (isset($_SESSION['post']['message']) ? $_SESSION['post']['message'] : ''); ?></textarea>
</li>
<input class="btn btn-default"type="submit" name="button" id="button" value="Submit" />
</ul>
<?php echo isset($success)?$success:''; ?>
</form>
As you can see, adding a POSSIBLE SOLUTION with header('Location: index.php#5'); makes my website come back to the contact form (not exactly what I wanted, but helps a bit), but it breaks the $success='<h1>Thank you!</h1>';.
Is there any easy way to do it (using my original code) with AJAX? Since I am not used to work with scripts.
In the other hand, could be a solution on display $success='<h1>Thank you!</h1>'; and make the function header('Location: index.php#5'); work on the same form?

Use Ajax to post data if you don't want to refresh the page.
See documentation here
$.post documentation
Or
Ajax

Use header and redirect the page.
header("Location:your_page.php");
You can redirect to same page or different page.
or
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
header('Location: index.php?msg=sucess');
}
if ( isset($_GET['msg']) && $_GET['msg'] == 'sucess' )
{
$success='<h1>Thank you!</h1>';
}

You can try this :-
By using session :
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
$_SESSION['thanks_msg'] = 'Thank You';
header('Location: index.php#5');
}
?>
On index.php file :-
check if the $_SESSION['thanks_msg'] is set or not, if set then displaythat session msg.
By using GET method :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
EDIT :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}

Related

undefined index when page is loaded

I'm having a issue where a variable is becoming undefined when the page is loaded individually...
So.
My front page has a address form where when the address is filled out and you click "Get your offer" it'll take you to another page where the address is carried over using $_POST['address'] in the value of the new input. so value="<?php echo $_POST['address']; ?>"
My problem is that when the offer page is loaded without using the front page form it gives me the error
<br /><b>Notice</b>: Undefined index: address in <b>C:\xampp\htdocs\offer\index.php</b> on line <b>228</b><br />Address
which makes sense. so i tried to fix it by putting this in the value= :
<?php
$carryover = $_POST['address'] or empty($carryover);
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
?>
which did absolutely nothing so.
Front page form:
<form method="post" action="/offer/index.php" name="front" id="front">
<div class="form-group">
<input type="text" id="autocomplete" onFocus="geolocate()" name="address" id="address" value="" placeholder="123 main st" required>
<button type="submit" class="theme-btn btn-style-nine"><span class="txt">Get your offer</span></button>
</div>
</form>
Form 2 on offer page (where address is carried over too):
<form class="multisteps-form__form" action="finish.php" id="wizard" method="POST" enctype="multipart/form-data">
<div class="col-lg-8">
<div class="form-input-inner position-relative has-float-label" >
<input type="text" name="address" id="address" placeholder="Address" value="<?php
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Address';
} else{
echo $carryover;
}
?>
" class="form-control" required>
<label>Address</label>
<div class="icon-bg text-center">
<i class="fas fa-home"></i>
</div>
</div>
</div>
</form
The undefined index notice happens when you read $_POST['address'] so any code you write after that isn't going to affect the notice.
Checking whether $carryover is empty is too late, you need to check if the $_POST index itself is empty.
Instead of:
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
You need to use:
if(empty($_POST['address']) {
echo 'Enter Address';
} else {
$carryover = $_POST['address'];
echo $carryover;
}
Instead of this:
$carryover = $_POST['address'] or empty($carryover);
use this:
$carryover = $_POST['address'] ?? '';

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

Can't pass a variable from one php file to another

I have a simple login page, and the idea is that if user input incorrect passowrd/login, then he or she will see error message on the same page. I have code in 3 different files - one is simple html, another has the functions, and last one runs all the logic:
<div id="content">
<div class="logo-container"><img src="images/logo2.png" alt=""></div>
<div class="container-fluid">
<!-- All login logic is in login.php file -->
<form action='/login-logic.php' method="post" class="form-1">
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" class="form-control" id="username"
name="username" placeholder="What's your username?" required />
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" class="form-control" id="password"
name="password" placeholder="What's your password?" required/>
<?php
if($isValid === false) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}
?>
</p>
<p class="submit">
<button id="submit-button" type="submit" name="submit" value="submit"><i class="fa fa-arrow-right"></i></button>
</p>
</form>
</div>
// Check match of the credentials in database
function loginValidation($query) {
global $isValid;
$isValid = true;
$count = mysqli_num_rows($query);
if($count == 1) {
header('Location: pages/signup.php'); /* Redirect browser */
} else {
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
}
Thank you!
You declare a variable just before to force browser to reload the page. So the variable is no more defined in the next request.
Here is a possible way.
Instead of :
{
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
Do :
{
/* Redirect browser */
header('Location: index.php?error');
exit();
}
Then, in HTML :
if (isset($_GET['error'])) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}

PHP Header Exceptions

I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);

PHP $_SESSION data not saving from page to page

I'm beating my head against the wall right now. I've been fiddling with this for hours, and I can't seem to figure it out.
My sessions data isn't saving when I navigate from one page to another. I've set this up in WAMP, BTW.
The cookies are being saved, and the sessions data only works when I reset it at the beginning of EVERY script. I'm not quite sure what to do here. It's probably something ridiculously stupid, but any input is greatly appreciated.
my login script:
<?php
include('../partials/_header.php');
include('includes/connectvars.php');
if(!isset($_SESSION['id'])) { //logged in?
if(isset($_POST['submit'])) { // form submitted?
if(!empty($_POST['email']) && !empty($_POST['password'])) { /* Check to make sure post isn't empty in case of JS override/disable */
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = sha1(mysqli_real_escape_string($dbc, trim($_POST['password'])));
/* query DB */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($dbc, $query) or die ("There was an error with your mySQL query:" . mysqli_error($dbc));
if(mysqli_num_rows($result)==1) { /* Check that matching row exists in users for login */
$row = mysqli_fetch_array($result);
$_SESSION['id'] = $row['id']; // set the session info
$_SESSION['type'] = $row['type'];
$_SESSION['name'] = $row['f_name'];
setcookie('id', $row['id'], time()+ (60*60*24*30));
setcookie('type', $row['type'], time()+ (60*60*24*30));
setcookie('name', $row['f_name'], time()+ (60*60*24*30));
$home_url = '/'; //redirect not working with $_SERVER variable in WAMP. keep an eye for the future
header('Location: '.$home_url);
mysqli_close($dbc);
} else { /* if no match in database ask to resubmit login info or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">Your email and/or password are incorrect. </label><br />
<label class="error">If you haven't already signed up, feel free to <a href="user_registration.php" > register</a> </label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}/* end conditional to check $rows array for username pw match */
} /* end conditional to check that form isn't blank */
else { /* If form is blank ask to resubmit or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must enter your email and password if you wish to continue.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
} // end else to resubmit in case of blank form
} /* end check if form has been submitted */ else{ /* prompt for login if page visited but login form not submitted */ ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must be logged in to do that!.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}
} /* end check if cookie isset */ else { //redirect if cookies & session is already set
$home_url = '/';
header('Location: '.$home_url);
}
?>
<?php include('partials/_footer.php'); ?>
this is my header (which includes the set session variable if cookie isset)
<?php //set session if isset cookie but not session
session_start();
if(!isset($_SESSION['id'])) {
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type'])) {
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];
}
} //end if !isset session verify
?>
and an example of the menu output depending on their session id:
<?php
if(isset($_SESSION['type']) && $_SESSION['type'] == "rnr") { //start special runner menu options
?>
<ul class="main_menu">
<li id="how_it_works" class="main_menu"><a class="main_menu" href="/user/bid_task.php">Bid on a task</a></li>
<li id="our_runners" class="main_menu"><a class="main_menu" href="/our_runners.php">Our Runners</a></li>
<li id="login" class="main_menu"><a class="main_menu" href="/user/my_account.php">My account</a></li>
<li id="register" class="main_menu"><a class="main_menu" href="/user/logout.php">Logout</a></li>
</ul>
<?php } /* end runner menu */ ?>
Thanks in advance.
The header file is included before the setcookie function is called in your login script. Based on what I see, the cookie is not set at the time you do this condition check:
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type']))
And because of that it never get inside the condition statement and following lines do not get executed in the header file:
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];

Categories