How to implement cookies on my login using php" - javascript

This is homework - I'm trying to make a login with cookies so that the browser remembers that you previously logged in but I have no idea how to implement it into my code. And to logout how can I delete cookies to login again?
<?php
session_start();
require_once('conexion.php');
$usuario=$_POST['usuario'];
$contrasena=$_POST['pass'];
$con=md5($contrasena);
$consulta= "SELECT * FROM usuarios WHERE usuario='$usuario' and contrasena='$con'";
$result= mysqli_query($link, $consulta);
$contador=0;
while($fila = mysqli_fetch_array($result))
{
$contador=1;
//cambiar por cookies
$_SESSION['id']=$fila['id'];
$_SESSION['nombre']=$fila['usuario'];
}
if($contador==0)
{
echo '<script type="text/javascript">window.location.assign("login.html");</script>';
}else{
echo '<script type="text/javascript">window.location.assign("index.html");</script>';
}
?>
This is my form:
<form action="validacion.php" method="POST">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Usuario" name="usuario" id="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Contraseña" name="pass" id="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">enter</button>
</div>
<!-- /.col -->
</div>
</form>

You should remember that sessions and cookies are not the same thing:
What is the difference between Sessions and Cookies in PHP?
Still with me?
You have to "set" a cookie on your validacion.php:
$username = $_POST['usuario']; //I would highly recommend that you clean the input.
setcookie("usuario", $username);
On your index.html page simply convert it to a php file by adding the php at the top of the HTML. Add a php listener that detects a user that is logged in. Please also remember to change your index.html to index.php
<?php
if (isset($_COOKIE["usuario"])) {
echo "Welcome ".$_COOKIE["usuario"];
}
?>
On your log out simply "unset" the cookies after making sure they exist.
if (isset($_COOKIE['usuario'])) {
unset($_COOKIE['usuario']);
}
I would highly recommend you lookup:
http://php.net/manual/en/function.setcookie.php &
http://php.net/manual/en/function.unset.php

Related

How to create a login script using PHP and JAVASCRIPT?

I have a php file for comparing the inserted data in input element of HTML.
then, if I click the button, I want to trigger it by JavaScript.
I have a sample code with php, if I used this in html file, this works perfectly fine, but then I have no idea on how to use this in JavaScript.
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
HTML:
<form action="" method="POST" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
First your code has alot of flops.
1.) You are saving password as plaintext, you will need to hash your password using php default password hashing mechanism.
2.) Your code is vulnerable to session Fixation attack. You can mitigate that using session regenerate_id as below
session_regenerate_id();
I will add it at your php script
3.) Session hijacking can only be prevented by ensuring that your site runs under https and not just http
4.) You are passing session username without sing htmlentities or htmlspecialchars functions.
Remember to do that when displaying session username on welcomepage.php
To answer your question, You can do that with Jquery/Ajax.
In the code below, am submitting your form using signin id attributes as can be seen in the jquery/ajax code below.
The code below displays all the actions triggered by the ajax/jquerycode
<div id="loader"></div>
<div id="result"></div>
Remember to include jquery.min.js files to ensure that it works
so here is your login.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
}
});
}
})
});
</script>
<form action="" method="POST">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
login.php
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
Finally, in case if the form does not get submitted, you can remove just tis two the form elements
<form> </form> and it will work
Updated section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
$('#fadeoutResult').delay(5000).fadeOut('slow');
}
});
}
})
});
</script>
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="password"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In Now
</button>
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
login.php
<?php
/*
//testing post data....
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = $_POST['username'];
echo $mypassword = $_POST['password'];
}
*/
include("php_functions/config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
There are many ways to collect data from a form, in my opinion the most practical is to use FormData. And the way to communicate javascript with php code is to use ajax. Please look at the following example.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" method="POST" name="index-login" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input
id="RememberMe"
name="rememberme"
type="checkbox"
/>
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button
type="submit"
class="btn btn-primary hidden-xs"
id="signin"
>
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
// You can access a form by its name,
// for example if the form had the name 'form' you could access it through
// `const form = document.forms.form`
// in your case by using the same name id value should be accessed thus
const indexLogin = document.forms["index-login"];
indexLogin.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
// Prevent submit form
event.preventDefault();
// Get data from inputs. Here this refer to the current form
const formData = new FormData(this);
// Inspect data collected
// for (const [key, value] of formData.entries()) {
// console.log(key, value);
// }
// Send form to php file
fetch("file.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(json => {
// do something
})
.catch(error => console.error(error.message));
}
But, your data will be visible through devtool in the network panel. I guess that will require another question.
I hope I have interpreted your question properly.

Can I reload a div using jQuery?

I have an area made up in a navigation by bar some PHP code that either shows a inline login form or the users username. The login form is submit using jQuery so no page load is required to set the users session variables etc. but how can I get around not having to refresh the page so that the correct text is shown (i.e. the users username rather than the inline form)?
At the moment the login works seamlessly without having to refresh the page but I need to somehow update that area also.
<div id="divLogin">
<?php if (!logged_in()) { ?>
<div class="form-group">
<input type="text" placeholder="Email" class="form-control" id="user">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control" id="pass">
</div>
<button type="button" class="btn btn-success" id="login">Sign in</button>
<button type="button" class="btn btn-primary" id="register">Register</button>
<?php } else { ?>
<div class="form-group">
<p>You are logged in as <strong><?php echo $_SESSION['user']; ?></strong></p>
</div>
<?php } ?>
</div>
You can do that using load() function or by using AJAX.
$('.your_button').on('click', function(){
$('#divLogin').load('your_page_url_here');
});

RSVP Form submitting after each response- Need All responses submitted together for family

This is for a private wedding website. Invitations are sent to guests, which could be individuals or entire families. Those invitations include a special Passcode that lets them access the website. Once inside, in the RSVP section we have returned the names of the guests invited.
The goal is to allow whichever guest that has logged in to respond to the RSVP by clicking a box that says "Yes" I'll be in attendance or "No" I won't be attending.
The question is available to all of the people in the group. Then the person can enter other info + offer a song suggestion for the wedding. I'd like at that point for the entire form to be submitted altogether.
PROBLEM: As soon as a guest clicks on (Yes) or (No) the form automatically submits, and then refreshes the page. At that point you can't see what selection was made any longer. How do I change this code so that my guests can click all of the yes's and no's and then entire the other information, where then they can see all of their responses before clicking Submit which submits() the whole form?
Ex:
John (Yes)
(No)
Emily (Yes)
(No)
Louis (Yes)
(No)
Mailing Address (form field)
Email Address (form field)
Phone number (form field)
Song Title (form field)
Artist (form field)
Button (Submit)
<!-- FORM -->
<div class="row">
<div id="result" class="col-md-12"> <!-- Show Message --> </div>
<div class="col-md-6">
<div id="events" class="form-group">
<?php
global $wpdb;
$guestname = $wpdb->get_results("SELECT * FROM `wp_password_a` where pwd_a_id='" . $_SESSION['admin_id'] . "' ");
$guest = $guestname[0]->name_guest;
$id_res = $guestname[0]->wp_response_id;
$myrows = $wpdb->get_results("SELECT * FROM `wp_pwd_a_response` where guestname='" . $guest . "' ");
//echo "<pre>";print_r($myrows);
$i = 1;
foreach ($myrows as $pro_data) {
?>
<form method="post" id="formName<?php echo $pro_data->wp_response_id; ?>" >
<div class="col-md-12">
<div class="col-md-4" style="margin:10px 0px;">
<?php echo $pro_data->member; ?>
</div>
<div class="col-md-4">
<div class="checkbox">
<label><input type="checkbox" class="checkbox" onchange="document.getElementById('formName<?php echo $pro_data->wp_response_id; ?>').submit()" name="response" value="YES">Will be in Attendance</label>
</div>
</div>
<div class="col-md-4">
<div class="checkbox">
<label><input type="checkbox" class="checkbox" onchange="document.getElementById('formName<?php echo $pro_data->wp_response_id; ?>').submit()" name="response" value="NO">Regretfully Declines</label>
<input type="hidden" name="res_id" value="<?php echo $pro_data->wp_response_id; ?>">
</div>
</div>
</div>
</form>
<?php } ?>
<form method="post">
<div id="fullname" class="form-group">
<label for="inputname"><i><b>Mailing Address</b></i></label>
<input type="text" name="address" class="form-control" id="inputname" placeholder="">
</div>
<div class="form-group">
<label for="inputname"><i><b>E-mail Address</b></i></label>
<input type="text" name="phone" class="form-control" id="inputname" placeholder="">
</div>
<div class="form-group">
<label for="inputname"><i><b>Phone Number</b></i></label>
<input type="text" name="phone" class="form-control" id="inputname" placeholder="">
</div>
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
<i></br></br>In celebration of the bride and groom’s special day, I would like to dedicate the following song:</i>
</div>
<div id="fullname" class="form-group">
<label for="inputname"></br></br><i><b>Song Title</b></i></label>
<input type="text" name="song" class="form-control" id="inputname" placeholder="">
</div>
<div class="form-group">
<label for="inputname"><i><b>Artist</b></i></label>
<input type="text" name="artist" class="form-control" id="inputname" placeholder="">
</div>
</div>
<div class="col-md-12 text-center text-danger"></br></br>
<div><b><i>Please provide a response by August 1, 2015.</i></b></div>
</div>
<div class="col-md-12 text-center">
<div class="form-group">
<input type="submit" id="submitButton" name="submitresponse" class="btn btn-default btn-lg" value="Submit">
</div>
</div>
<form>
</div>
</div>
</section><!--END of RSVP SECTION-->
Based on the code sample you provided, it appears you are creating a new form for each checkbox, which is separate from the form containing the other information. Furthermore, in the generated checkbox forms, you have the code:
onchange="document.getElementById('formNamewp_response_id; ?>').submit()"
This explains the behavior you are seeing when the checkbox is clicked and the page refreshes. The onchange event fires, and the form submits.
To achieve the behavior you are looking for, render each your checkbox inputs into the lower form, and remove the 'onchange' handler on each checkbox input. Then when you submit the form, all fields will be submitted at once. Just make sure that the endpoint you are POSTing to properly handles the new fields.

Echoing/outputting information that was added to an input field on the same page

I'm creating a checkout system. I have three parts to it:
Shipping info
Payment info
Order confirmation
I'm trying to figure out a way that when the customer enters their shipping information, that data can be echo'd out onto my order confirmation part, so they can confirm that is where they want it shipped to.
The way I designed my checkout system is that all three parts are on the same page. Only one part shows at once and the others are hidden until the customer would click 'Proceed to xxxx'. When they click that Proceed button, nothing is being sent. It is just taking the div and showing it and hiding the previous div. Nothing is sent until when the customer clicks Submit order on the confirmation div.
I validate the fields and assigned them to variables so I can post the shipping and product info into my db.
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
$streetline1 = trim( $_POST['streetline1'] );
$streetline2 = trim( $_POST['streetline2'] );
$city = trim( $_POST['city'] );
$state = trim( $_POST['state'] );
$zipcode = trim( $_POST['zipcode'] );
$phone_number = trim( $_POST['phone_number'] );
$email = ( $_POST['email'] );
//etc...
Shipping Information Section:
<div class="shippinginfocontainer">
<span class="summarytitle">
<p>Enter Shipping Information</p>
</span><br>
<div class="center">
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center">
<input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline1">Street Line 1</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline1" value="<?php echo escape($user->data()->streetline1); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline2">Street Line 2</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline2" value="<?php echo escape($user->data()->streetline2); ?>">
</div>
</div>
<div class="field">
<label class="paddingleft" for="city">City</label>
<div class="center">
<input type="text" class="biginputbarinline" name="city" value="<?php echo escape($user->data()->city); ?>" required>
</div>
</div>
</div>
<div class="formleftcenter">
<div class="field">
<label for="state">State</label>
<input type="text" class="mediuminputbar" name="state" value="<?php echo escape($user->data()->state); ?>" required>
</div>
<div class="field">
<label for="Phone Number">Phone Number</label>
<input type="text" class="mediuminputbar" name="Phone Number" value="<?php echo escape($user->data()->phone_number); ?>">
</div>
</div>
<div class="formrightcenter">
<div class="field">
<label for="zipcode">Zip Code</label>
<input type="text" class="mediuminputbar" name="zipcode" value="<?php echo escape($user->data()->zipcode); ?>" required>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" class="mediuminputbar" name="email" value="<?php echo escape($user->data()->email); ?>" required>
</div>
</div>
<div class="clear">
<button class="checkoutbutton" id="button2">Proceed to Payment Information</button>
</div>
</div>
I won't add my payment part as it is irrelevant to this question.
Then this is the relevant part of the Confirmation part. I wasn't sure how to do this, so I just wrote in echo's to show what I am trying to do.
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p><?php echo $fullname; ?></p>
<p><?php echo $streetline1; ?></p>
<p><?php echo $streetline2; ?></p>
<p><?php echo $city . $state . $zipcode; ?></p>
</div>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input class="widebutton" type="submit" value="Place Your Order">
Is there a way to do this with keeping this all on the same page? I really do not want to have multiple pages for this and I like the way I have all of this formatted. I just can't figure out this part.
You could possibly use AJAX via serialize() of your form when you click a review button (as Matthew Johnson suggested). Second idea is something like this where you copy from one input to another, in a different part of your page. It would take a bit more work to set up than something like AJAX because you are basically duplicating a form. Using .html() inside a div or span placeholder would probably work too:
HTML:
<input type="text" class="copy-from" data-copy="name" name="name" />
<input type="text" class="this-elem" id="name" disabled />
CSS
.this-elem {
border: none;
font-size: 18px;
color: #333;
}
jQuery
$(document).ready(function() {
$(".copy-from").keyup(function() {
var ElemId = $(this).data('copy');
$("#"+ElemId).val($(this).val());
});
});
Demo
http://jsfiddle.net/fh5kfhtm/4/
EDIT: AJAX/PHP Solution
<!-- This is the placeholder for the data after submission -->
<div id="final"></div>
<!-- FORM, well really simplified form -->
<form id="orderform" method="post" action="process.php">
<input type="hidden" name="order_form" />
<input type="text" name="address" />
<!--
This triggers the ajax (you would use your
"Proceed to Order Confirmation" button)
-->
<div id="confirm">CONFIRM</div>
<input type="submit" name="submit" value="ORDER" />
</form>
new.php
File name/path must match what's in the AJAX url
<?php
if(isset($_POST['order_form'])) {
print_r($_POST);
exit;
}?>
jQuery AJAX
<!-- GET THE LIBRARIES (YOU SHOULD ALREADY HAVE THEM) -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#confirm").click(function() {
$.ajax({
// This is where you need the right path to the new php file
url:'/path/to/new.php',
type: 'post',
data: $("#orderform").serialize(),
success: function(response) {
$("#final").html(response);
}
});
});
});
</script>

A singular behavior about a Registration form in PHP

I have a registration form in my (project of) website of the following form: (i used bootstrap framework):
<div id="main-box" class="container">
<div class="row-fluid">
<div id="signup">
<div id="float"></div>
<div id="center_signup">
<h3>Registrazione Studente</h3>
<?php if (isset($registerError)): ?>
<p><?php htmlout($registerError); ?></p>
<?php endif; ?>
<form action="" method="post" class="form-horizontal">
<div class="form-group">
<label for="nome" class="col-sm-2 control-label">Nome: </label>
<div class="col-sm-6">
<input type="text" name="nome" id="nome" class="form-control">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email: </label>
<div class="col-sm-6">
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-6">
<input type="password" name="password" id="password" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Now the data of the form are managed from a index.php controller file, which do this (the register.html.php file is the template file in which there is the code above):
if (isset($_GET['register']))
{
include 'register.html.php';
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['registerError'] = 'fill in both fields';
exit();
}
$password = md5($_POST['password'] . 'figarodb');
if (databaseContainsUser($_POST['email'], $password))
{
$GLOBALS['registerError'] = 'Student already registered.';
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/db.inc.php';
// Puts the student in the relevant table
try
{
$sql = 'INSERT INTO studente SET
nome = :nome,
email = :email,
password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':nome', $_POST['nome']);
$s->bindValue(':email', $_POST['email']);
$s->bindValue(':password', $password);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Errore in student registration.';
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
This header might redirect at the home page, but it doesn't do it!
If instead of the page with bootstrap and javascript code, i modify the registration page in this way:
<body>
<h1>Registration</h1>
<form action="" method="post">
<?php if (isset($registerError)): ?>
<p><?php echo $registerError; ?></p>
<?php endif; ?>
<div>
<label for="name">Nome completo: <input type="text" name="nome"
id="nome"></label>
</div>
<div>
<label for="email">Email: <input type="text" name="email"
id="email"></label>
</div>
<div>
<label for="password">Password: <input type="password"
name="password" id="password"></label>
</div>
<div>
<input type="submit" value="Invio">
</div>
</form>
</body>
now the controller redirect at the home page correctly!
I can not explain this behavior, any help will be greatly appreciated!Thanks!
In your php file there is written :
header('Location: .');
Maybe your web application is redirected on index.html by default because it's the default root.

Categories

Resources