Page refresh after login? - javascript

I am trying to get my page to refresh after login this is the format of my index.php
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
// let the user login
include "login.php";
}
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
Inside my login.php
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['email'];
$uid = $row['u_id'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['uid'] = $uid;
$flag=1;
header("Location: http://5aday.dihops.net/index.php");
// echo "<meta http-equiv=\"refresh\" content=\"0;index.php\">";
//header("Refresh: 2; url=http://5aday.dihops.net/index.php");
// THIS IS WHERE I AM STUCK
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
?>
}
?>
I dont know what I am doing wrong. But once the user gives his username and password and submits it .... I get a blank page. and the user has to manually refresh the webpage to see the content of the webpage.

As per the link mentioned the header(location) must be placed at the top of the page ... So I rearranged the if conditions ....
I added this at the top of the index.php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
include "login.php";
} ?>
then in the body i added the other if statements
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}else
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
}
That has fixed the problem.

You have no content under:
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}
So.. when you log in, there's nothing to see.
It doesn't seem there's any HTML elements for JavaScript to grab a handle on and edit either. Unless you're using JavaScript to then create elements from scratch. If so, have you checked that the JavaScript has even loaded? Also, check for errors in the console.

Try this code
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
echo "Welcome".$_SESSION['Username'];
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
// let the user login
include "login.php";
}
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>

Try using PHP_SELF for redirect the same page
header('Location:'.$_SERVER['PHP_SELF']);
it might help

Stay page after Login, Refresh page. try JAVASCRIPT in php
echo "<script>window.location.replace('/')</script>";

Related

Access session value

How to make a form style hidden if a specific session is set?
I did it that way
<form action="" method="post" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>
<input type="radio" name="log" id="viso" value="vis" checked onclick="javascript:yesnoCheck();"> Visitor<br>
<input type="radio" name="log" id="uso" value="use" onclick="javascript:yesnoCheck();" > User<br>
<label name="frm" id="frm" style="display:none" ><b>Password</b></label>
<input type="password" style="display:none" name="pw" id="pw" placeholder="Enter Password" >
<input type="submit" >
</form>
<?php
if ( isset ($_POST['log'])&& $_POST['log']=="vis" )
{
$_SESSION["visitor"]="true";
unset($_SESSION["start"]);
}
else if ( isset ($_POST['log'])&& $_POST['log']=="use" )
{
if ( isset($_POST['pw']) && $_POST['pw']!="1111" )
echo "Wrong password";
else if ( isset ($_POST['pw'])&& $_POST['pw']=="1111" )
{
$_SESSION['start']="Welcome";
unset($_SESSION["visitor"]);
}
}
?>
but it's only hidden if i press on the submit button twice not from the first time
You have a simple logical flaw .You are checking for session before you set them .When user fills form and submits , your php runs this
<form action="" method="post" id="lol" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>
Note that at this time no session is set so form will not have display:noneand will get displayed **even though user has entered his details correctly still when response come form will be visible.Now to fix the issue move your session check before form display code
<?php
if ( isset ($_POST['log'])&& $_POST['log']=="vis" )
{
$_SESSION["visitor"]="true";
//....more stuff
//...
} ?>
<form action="" method="post" id="lol" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>

can't post the data from form on a pop-up?

i would like to made a pop-up window for my login and signup sites. but there's a problem with this code, can't post the data from the form and the submit button didn't work when clicked. someone help me please. thanks.
here it is the index.html with the pop-up:
<div class="popup">
<h2>Welcome Guest!</h2>
<form id="formlogin" name="formlogin" method="POST" action="login_proses.php" enctype="multipart/form-data" autocomplete="on">
<p>Please enter your login and password here</p>
<p>
<label for="username">Login</label>
<input type="text" id="username" name="username" value="" required />
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password" value="" required/>
</p>
<p>
<input type="submit" value="Log In" onclick="popupUploadForm()">
</p>
</form>
<a class="close" href="#close"></a>
</div>
<script>
function popupUploadForm(){
var newWindow = window.location.href='login_proses.php';
}
</script>
and here it is login_proses.php that pick the data form, but it's always failed, and always go into index.html as else condition.
<?php
session_start();
include "connect.php";
if (isset($_POST["username"])){
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql=mysql_query("select * from member where username='$username'");
if ($sql && mysql_num_rows($sql)>0){
$result=mysql_fetch_array($sql);
if($password == $result['password']){
$_SESSION['username']=$username;
echo "<script type='text/javascript'>alert('Selamat Datang $username');
window.location.href='member.php';</script>";
}
else{
echo "<script type='text/javascript'>alert('Password salah, silahkan coba lagi');history.go(-1)</script>" ;
}
}
else{
echo "<script type='text/javascript'>alert('Username tidak ada dalam database');history.go(-1)</script>" ;
}
} else {
header("location:index.html");
} ?>

Two form on a single page : How to identify which form validate using jquery ajax function

I have a html page which contains
a form with fields for sign up (registration / new member)
a form for sign in (login for already member)
The sign in form is :
<form class="dialog-form">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>PAssword</label>
<input type="password" placeholder="My PAssword" class="form-control">
</div>
<input type="submit" name="sign_in" value="Connexion" class="btn btn-primary">
</form>
The sign up form is :
<form class="dialog-form" action="bat/user_validation.php" method="post">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="My secret password" class="form-control">
</div>
<div class="form-group">
<label>Repeat Password</label>
<input type="password" placeholder="Type your password again" class="form-control">
</div>
<input type="submit" name="sign_up" value="Inscription" class="btn btn-primary">
</form>
One the other side, I have a php script file which contains function to check and insert a userid.
function getPassword($utilisateur) {
try {
$dbh = new PDO(DSN, USER, PASS);
$uid = $utilisateur;
$sql = "SELECT password FROM cc_users WHERE uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':uid'=>$uid));
$result = $sth->fetchAll();
return (count($result) == 1) ;
} catch (PDOException $e) {
print "Erreur ! : " . $e->getMessage() . "<br/>";
die();
}
}
function setPassword($uid, $pass) {
$dbh = new PDO(DSN, USER, PASS);
$sql = "UPDATE cc_users SET password =:pass where uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':pass'=>$pass ,':uid'=>$uid));
echo $count = $sth->rowCount();
return $dbh->exec($sql);
}
function newPassword($utilisateur, $pass) {
$crypt = crypt($pass);
return setPassword($utilisateur, $crypt);
}
function checkPassword($utilisateur, $pass) {
if (empty($pass)) return FALSE;
$interne = getPassword($utilisateur);
$crypt = crypt($pass, $interne);
return ($interne === $crypt);
}
print_r($_POST);
My questions are :
How I can check on which form the user is coming?
How can I do an $.ajax call for checking the form? If yes how?
Thanks
HTML:
Form 1:
<form id="form1">
<input type="submit" value="submit" />
</form>
Form 2:
<form id="form2">
<input type="submit" value="submit" />
</form>
jQuery:
$('form').on('submit', function () {
console.log($(this).attr('id')); // Logs the id of the submitted form
});
Give name for <form>
<form class="dialog-form" name="signin">
<form class="dialog-form" action="bat/user_validation.php" method="post" name="signup">
You can check $_POST global to see if it contains the name of your <input type="submit" />. It will contain either sign_up or sign_in, depending on what button did the user press.
For example:
if(isset($_POST['sign_up']){
$signingUp = true;
}
If you want to submit the form using jQuery ajax, you can use the following code snippet:
$.post('bat/user_validation.php', $('form.dialog-form').serialize());
Though the selector should be more concrete, probably including a form ID to distinguish between the two forms.

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

preventDefault() won't work with form.submit()

I'm trying to get my login form to either close my lightbox, or change the text of an errorbox depending on whether or not the login attempt was a success. I'm not sure, but i think it has to do with my
onclick="formhash(this.form, this.form.password);"
which is a JS function that hashes a password, then continues the form submit. it ends with
form.submit();
Here's my code:
HTML:
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
JS:
<script>
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
return false;
});
})(window.jQuery);
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['error'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
When I log in, the preventDefault() doesn't work. It opens process_login.php in a new page and displays "{"success":true}" on a blank page. Any suggestions? (keeping in mind that it needs to be as secure as possible)
You could try moving it all into a single handler call. By changing the type="button" to type="submit" on your form.
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="submit" class="searchform" value="Submit" size="40" style="height:45px; width:90px" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
Then you could move your formhash function into the submit function
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
formhash(var1, var2);
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
...//the rest of your code

Categories

Resources