How to write a multi-step registration form in one page? - javascript

I want to make a multi step registration form. When user enters his name it, it checks in the database whether that username exists or not, then it should go to 2nd step where he will enter new password and once submitted for that username an OTP will be sent to registered mobile number.
In 3rd step OTP confirm page should open and on giving correct entry the process should be completed. I have written a basic code to achieve this, but I want it to happen step by step, in one page itself.

For this functionality you have to work with ajax
for example when user enter username you can post request like this
.JS file
var username = $('#username_textfield_id').val();
$post('ajax.php',
{data:username}
).success(function(responce){
if(responce == 'available')
$('#password_field').css({display:'block'}); // password field will be hidden by default
else
alert(responce);
});
You can call above function on focus out of text field or you can put button. :-)
ajax.php file
<?php
$username = $_POST['data'];
/* check username in database */
if(username available )
echo "available";
else
echo "username already taken";
?>
as per this files you can make steps in form.
you form will be something like this
<input type="text" id="#username_textfield_id"> </br>
<input type="text" id="#password_field" style="display:none"></br>

make 4 small php files for each step. Each php should check if it is valid for rendering.
if(!user.hasEmail())
else if(user.hasEmail() & !user.haspassword())
include php1
else if(user.haspassword() && !user.hasAddress())
include php2
else if(user.hasAddress && !user.isconfirmed())
include php3

Related

Implementing required user login with jQuery File Upload

I am needing a suggestion on the easiest way to implement required user login for the jQuery File Upload. On the site home page users login with an email and password. We are then using $_SESSION[email] site wide to allow or disallow accessing of pages depending on whether or not the user is logged in.
So far this has worked fine on all PHP pages and below is the example of the code being used:
<?php
// at the top most of the page
session_start();
// Checking user login credentials
if(!isset($_SESSION['email'])){
// Alerting the user they must be logged in
echo "<script>alert('You must be logged in to access this page.')</script>";
// Sending the non-logged in user back to the home page
echo "<script>window.open('../index.php','_self')</script>";
}
// If the user is logged in let them see the page
else { ?>
// added to the very last line of the page
<?php } ?>
The login form is below in case you need to see that:
<form method="post" action="#">
<table width="90%" border="0" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="login" id="login" value="Login"></td>
</tr>
<tr>
<td colspan="2" align="center"><h3 style="margin-top:7px;">Forgot Password?</h3></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br />Sign Up is <em>quick</em> and <em>easy</em>!</span></div></td>
</table>
</form>
This is the Login PHP file:
<?php
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
// Let's get the mail and password from the Login Form
$email=$_POST['email1'];
$password= ($_POST['password1']);
// Let's see if the entered email is in the database and if it is retrieve the password
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
// Create variables for the database result, password and email
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];
// If the email and password match up
if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {
// Start a session bound to the email
$_SESSION['email']=$email;
// Alert the user of a successful login
echo "Successfully Logged in.";
// Make a variable for the date and time
$mysqltime = date ("Y-m-d H:i:s");
// Update the database to show the time of the user's last successful login
mysqli_query($conn, "UPDATE nonadmin_user_login SET last_login='$mysqltime' WHERE email ='".$email."' ") or die(mysqli_error($conn));
}
// Alert the user of a failed login
else{
echo "Email or Password is wrong please try again.";
}
?>
And this is the Login JS:
<script>
// Let's get this party started
$(document).ready(function(){
// Binding this to the login form submit button
$("#login").click(function(){
// Setting variables and binding them to the login form fields
var email = $("#email").val();
var password = $("#password").val();
// Checking if the email or password is empty
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
// Alerting the user of empty email and/or password
alert("Please fill all fields.");
// If the fields are not empty
}else {
// Posting the entered email and password to log-me-in.php
$.post("log-me-in.php",{ email1: email, password1:password},
// Function to event handle incorrect email or password
function(data) {
// If the email is invalid
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
// Alert the user of invalid entry
alert(data);
// If email and/or password don't match the database query
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
// Alert the user of invalid entry
alert(data);
// If nothing went wrong so far it's time to login and alert user of login success
} else if(data=='Successfully Logged in.'){
// Let's refresh the window so the sidebar signin block can swap to the logged in block
window.location=window.location;
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>
I have tried several methods and all of them failed. I tried using the standard code (uppermost code sample box) used on all other pages at the top of the jQuery File Upload index.html and it's a no go.
I also tried to add this standard code (uppermost code sample box) to the jQuery File Upload UploadHandler.php where the #session start line of code is...
protected function get_user_id() { //
#session_start();
return session_id();
}
...and once again it did not work. The way it stands now anyone on earth can open the jQuery File Upload page and start loading files which is not okay. My thought is maybe I need to give up on not displaying the whole page if the user is not logged in and just let the page display... and then if the upload file button is clicked at that point fail the upload if they are not logged in?
If you have a suggestion how to block the whole page based on login let me know. If you have a suggestion on how to block the file upload based on login let me know. If you have any suggestions on anything at all let me know I am all ears and thanks in advance for any help you can lend!
Why not just check if
if(isset($_SESSION['email']))
is set and if so execute file upload script, if not, don't run the script and return an error
if(!isset($_SESSION['email']))
{ actual upload script }
else
{ echo "I dont think so hombre" }

Javascript doesn't work on WAMP but works fine without it

I just started learning PHP and WAMP. Before that I created a set of webpages using HTML,CSS, and JS. The JS is for validating the form, and if everything goes well it will jump to a php page that insert data into sql database.
The simplified form.html and validation.js are:
function validation() {
var emailCheck = email.search(/^[a-zA-z0-9_]+\#[a-zA-z0-9_]+\.[a-zA-z]{2,3}$/);
if (emailCheck==-1) alert("Please enter a valid email address");
else document.getElementById("signup").action = "success.php";
}
The Form code
<form id="signup" class = "signup" method="POST">
.....
<input type="text" name="email" id="email" required/>
....
<button class = "button3" onclick = "validation()">Submit</button>
</form>
The success.php is simply to insert data to the mySQL database.
Now I run the form.html without using the localhost, the javascript works perfectly. The alert window shows up if I enter wrong stuff.
If I run localhost/form.html with WAMP, when I enter wrong stuffs, the javascript doesn't work. The alert window doesn't show up. BUT when I pass the validation, it successfully jumps to the success.php.
Therefore, I consider the Javascript is working but somehow part of it doesn't since the javascript is the only connection between the form.html and success.php.
Any idea?
variable "email" is undefined, so you can't using search function on a undefined variable. You need get the email value first.
function validation() {
var emailCheck = document.getElementById("email").value.search(/^[a-zA-z0-9_]+\#[a-zA-z0-9_]+\.[a-zA-z]{2,3}$/);
if (emailCheck==-1) alert("Please enter a valid email address");
else document.getElementById("signup").action = "success.php";
}

Prevent Multiple Form Submissions, PHP

I have a form, something like:
<form action="" method="post">
<label class="reg_label" for="name">Name:</label>
<input name="name" type="text" class="text_area" id="name"/>
.... etc...
</form>
To submit the form, the user must also first complete a CAPTCHA. This works great, and only allows form submission for perfect matches. Reloading the page will result in a new CAPTCHA. Pressing the "back" button will also display a new CAPTCHA.
When the user submits the form, it is verified via javascript, and that all works dandy, and then it is submitted (and emailed) via a separate php script:
<?php
include('connect_to_mysql.php');
$webMaster = 'my#email.com';
$name = mysqli_real_escape_string($db_conx, $_POST["name"]);
$phone = mysqli_real_escape_string($db_conx, $_POST["phone"]);
$email = mysqli_real_escape_string($db_conx, $_POST["email"]);
$message = mysqli_real_escape_string($db_conx, $_POST["message"]);
$emailSubject = 'Contact Form Submission';
$body = <<<EOD
Name: $name
Email: $email
Phone: $phone
Message:
$message
EOD;
$headers = "From: $email\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
header('Location: ../thankyou.html');
?>
This all works as expected, and I am satisfied with the escape strings for now. The form catches non-emails, and the CAPTCHA works every time. But some clown just sent me 128 SIMULTANEOUS form submissions, and I am wondering how this individual did it.
Every field was filled out "9999.9". When I try it, I get errors for the name, phone number and email. I can't even submit the form with that data. Even if I could, I would only be able to send it once because of the CAPTCHA (PHP).
The only hole I can see, and it IS a hole (just tried it), is to type in the URL of the external script directly. So, a bad guy could write his own script, assign the variables (to POST) and then call my contact function 128 times.
While I'm working on righting that wrong, are there any other obvious gaping holes that someone could use for multiple form submissions like that, while bypassing the CAPTCHA (which is PHP)? Obviously just turn off JS to get around the validation.
I can post more code if needed, but just assume the JS is turned off, leaving only the PHP CAPTCHA check - which has nothing to do with the actual submission of the form, and changes on BOTH "back" and "reload" operations.
Thanks in advance.
CAPTCHA CODE
Captcha.php
<?php
session_start();
$rand = md5(rand(0,999));
$value = substr($rand, 10, 5);
$_SESSION['cap_key'] = $value;
... do some drawing stuff to make the CAPCHA, which is an IMAGE and cannot be read without some fancy character-recogntion code...
?>
Within the contact form file (called when form submitted)
<?php
session_start();
if ($_POST['submit'])
{
if ($_POST['captcha'] == $_SESSION['cap_key']) // Success
{
include('scripts/contact.php');
}else if($cap != 'Eq') // If wrong captcha entered
{
... reload page after sanitizing the inputs...
}
}
?>
But like I said, the CAPTCHA changes every reload of the page.
Thanks again.

Calling PHP function from Javascript then change form action

I'm trying to change my form action in my HTML then submit using javascript.
The conditions are in PHP .
I need help if anyone can assist me.
This is my PHP function :-
<?php
error_reporting(0);
if(isset($_POST['email'])){
$email=$_POST['email'];
if(!empty($email)) {
$chrono = 0;
} else {
$chrono = 1;
}
}
?>
The motive of the PHP is to check null email entry.
Here's the javascript function :-
<script type="text/javascript">
function fireform(val){
// missing codes
document.forms["demoform"].action=val;
document.forms["demoform"].submit();
}
// missing codes
</script>
HTML :-
<form name="demoform" action="">
<input type ="text" name="name" id="name">
<input type="hidden" name="buttonpressed" id="buttonpressed">
<input type="button" value="submit B" onclick="fireform('b')">
I want to do it in a way , when the user entered an empty email , the PHP will read it as chrono = 0.
Then goes to javascript , if the chrono equal to 0 , the action will remain empty.
If the chrono = 1 , the javascript will change the action of the form and submit.
I need help thanks.
Your flow is unclear: it seems that you want to change the form action from PHP, but PHP is triggered after the form submission. So there's something weird in your flow. You also don't seem to have a field called email in your markup. Add it (or rename the field name):
<input type="text" name="email" id="email">
Nonetheless, having an empty action means the form will be submitted to the page itself.
Probably what you need is a client side validation of the email field. In the fireform() JavaScript function, just add a check for email field:
function fireform(val){
if (document.forms["demoform"].email.value.length > 0){
document.forms["demoform"].action = val;
document.forms["demoform"].submit();
}
}
This should be enough to get what you need.
I would recommend checking the email field (for being empty) in javascript, and when you have set the proper action submit the form in javascript.
Check the field:
$('#<enter id of field>').val();
Update the action:
$('form').attr('action', 'Enter your updatet action here');
Submit the form:
http://api.jquery.com/submit/

Issue with Passing Form Values and Session session_start();

Hi I have an inquiry form with 3 steps
Step 1: small inquiry form (which is currently passing form fields to the step 2 page)
Step 2: full page inquiry form (this form submits and processes data via form processing script - form-process.php which then redirects user to thank you page and sends email to site admin)
Step 3: Thank you page (this page is in Joomla while the above two pages are standalone PHP pages accessed via FTP. )
I'd like to print the form fields (from the form in step 2) to the thank you page.
I am currently using php session to transfer field values from step 1 to step 2 which is working fine, however the same code doesn't bring form value from step 2 to thank you page.
My code is
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
I also use in every single page.
<?php
if(isset($_SESSION['error_msgs'])){
$_SESSION['error_msgs'] = '';
unset($_SESSION['error_msgs']);
}
if(isset($_SESSION['sucess'])){
$_SESSION['sucess'] = '';
unset($_SESSION['sucess']);
}
if(isset($_SESSION['form1data'])){
$_SESSION['form1data'] = '';
unset($_SESSION['form1data']);
}
?>
Can someone help why i am not able to pass values from step 2 to thank you page? I have also put the session() code into the form processing script which fires after step 2 submit button.
i have just added the below code into thank you page and it says below message.
Notice: A session had already been started - ignoring session_start() in /tmp/html1jVKJt on line 5
No data
the code i have placed on confirmation page.
<?php
if(isset($_SESSION['error_msgs'])){
$_SESSION['error_msgs'] = '';
unset($_SESSION['error_msgs']);
}
if(isset($_SESSION['sucess'])){
$_SESSION['sucess'] = '';
unset($_SESSION['sucess']);
}
if(isset($_SESSION['form1data'])){
$_SESSION['form1data'] = '';
unset($_SESSION['form1data']);
}
?>
but form field (first name) is still not printing on the confirmation page.
So it seems like the session is passing from step 1 to step 2 to step 3 (confirmation page) however is not printing the input field.
I am using into confirmation page to show submitted email.
<input type="text" value="<?php echo $_SESSION['user_email']; ?>"/>
Any feedback will be appreciated. thanks

Categories

Resources