Jquery registration and authorization forms. Making a great registration system using PHP, MySQL and jQuery

In this article, we'll look at step-by-step registration using jQuery.

If registration on your site requires filling out several dozen fields, it is very irrational to place them on one page. After all, the user is a very lazy creature and will not want to fill out all these fields.

An alternative option is to split registration into several steps. This immediately generates many positive responses - after all, when starting to perform steps, the user most often has a desire to finish them.

It is also logical to break the registration into logical blocks - contact information, address, personal data, and so on.

For step-by-step registration, there is no need to create several forms and send data separately to the server. It is much more convenient to place everything in one form, but show the user only a certain part of the form at each step. This is exactly the logic in our example.

In addition to logic, it is worth considering that at first only the link is visible "Forward"/"Next step", and at the last step it is not visible, but it is visible "Back" And "Registration".

Let's look at the example itself:

Page

Step 1

Login:

Email:

Password:

Step 2

Name:

Surname:

Age:

Step 3

A country:

City:

Street:

Back Next step

body ( margin:0; ) /* General styling is over */ form ( width:30%; margin:0 auto; ) form div.step ( display:none; ) form div.step p.step( text-align:center ; font-size:28px; ) form div.step p( ) form div.step p input( float:right; ) a.back ( display:none; ) form input ( display:none; ) a ( color:#006600 ; text-decoration:none; ) form p.talign( text-align:center; )

We will place the script responsible for switching steps in js/steps_registration.js, do not forget to also include the jQuery library:

$(document).ready(function() ( // Wait for the page to load var steps = $("form").children(".step"); // find all the steps of the form $(steps).show(); / / show the first step var current_step = 0; // set the current step $("a.next").click(function())( // Click event on the "Next step" link if (current_step == steps.length-2) ( // check if the next step will be the last $(this).hide(); // hide the "Next step" link $("form input").show(); // show the "Registration" button ) $(" a.back").show(); // show the "Back" link current_step++; // increase the counter of the current slide changeStep(current_step); // change the step )); $("a.back").click(function( )( // Click event on a small image if (current_step == 1) ( // check if the previous step is the first $(this).hide(); // hide the "Back" link ) $("form input") .hide(); // hide the "Registration" button $("a.next").show(); // show the "Next step" link current_step--; // decrease the counter of the current slide changeStep(current_step);// change the step)); function changeStep(i) ( // step change function $(steps).hide(); // hide all steps $(steps[i]).show(); // show the current one ) ));

We will not write the PHP sending code here, since it is not entirely relevant to this lesson. It is only worth noting that the letter is sent to the address specified in the first step of the form. In any case, you can download the demo files and see for yourself.

We decided to supplement with some examples published on Habré so that you can learn about some " innovative techniques"improving registration and authorization forms.

We simplify registration forms

So, a few tricks:

  • no need to duplicate password entry;

To make life easier for the user (why do this is well shown in this from Google), it is better to make one field and a checkbox that will remove the “mask” - all this is done using a small javascript code.

// // //

1. jQuery library.

2-7. initialization on element.

B. The HTML code of the form is as follows:

Login: Password:

5-6. The visibility of these fields is switched by the script using a checkbox.

B.init.js

$(document).ready(function())( $("#testpassword1").showPassword(); $("#testpassword").showPassword(".checker", ( text: "Custom checkbox", name: "showmypass " )); ));

G.styles.css

Body ( font-family: Arial, Helvetica, serif, sans-serif; ) form ( margin: 15px 0; padding: 15px; background: #ccc; color: #000; border: 1px solid #aaa; width: 500px; ) form label.form ( float: left; width: 120px; display: block; ) form input#testpassword1, form input#testpassword ( float: left; display: block; ) .clear ( clear: both; ) div.checker ( clear : both; display: block; border: 1px dotted #2d2d2d; color: #2d2d2d; background: transparent; width: 230px; font-size: 0.8em; margin: 20px 0 0 0; )

  • It’s better to autofill fields based on the entered data;

The less the user needs to enter, the better. Some fields can be filled in based on previous, already entered data. For example, you can populate the "city" field by reading and processing the value from the "index" field. A simple Ajax request and it's done. Using AJAX to obtain data about the city and region from the postal code.

A. We include libraries in the ‹header›:

1. jQuery library.
2. Main script.

B. The HTML code of the form is as follows:

ZIP code City Country

1.The field in which the postal code should be entered.

B. zip_city.js:

Function fillcitystate(controlname)( var zipcode = trim(controlname.value); //trim spaces if(zipcode.length!=5)( //check length return false; ) var zipstring = ""; xmlhttp = new XMLHttpRequest() ; xmlhttp.open("GET", "php/zip_city.php?zip=" + zipcode, true); //send the request to php xmlhttp.onreadystatechange=function())( //when receiving the result if (xmlhttp.readyState= =4)( var zipstring = xmlhttp.responseText; if (zipstring!="Error")( var ziparray = zipstring.split("|"); document.getElementById("txtCity").value = ziparray; //set the values for the city field document.getElementById("txtCountry").value = ziparray; //set values ​​for the country field ) ) ) xmlhttp.send(null); ) //space trimming function function trim(s) ( var l=0; var r=s.length -1; while(l< s.length && s[l] == " ") { l++; } while(r >l && s[r] == " ") ( r-=1; ) return s.substring(l, r+1); )

D. zip_city.php: ajax request handler.

Require_once("db.php"); $db_table = "zip_city"; //default return value $returnval = "Error"; //getting a GET parameter $zipcode = $_GET["zip"]; //preprocessing if (strlen($zipcode)>5)( $zipcode = substr($zipcode, 0, 5); ) if (strlen($zipcode)!=5)( die ($returnval); ) //receiving values ​​from the database $query = "SELECT * FROM ($db_table) WHERE zip="($zipcode)""; $resultval = mysql_query($query) or die("Cannot run query:Query: ".$query."".mysql_error($conn)); $rowcount = mysql_num_rows($resultval); if ($rowcount==1)( $row = mysql_fetch_array($resultval); $returnval = $row["zip"]."|".ucwords(strtolower($row["city"]))."|" .$row["country"]; //actually, generating a successful response ) echo $returnval;

D. db.php: database connection configuration.

//database connection settings $dbhost = "localhost"; $dbusername = "root"; $dbpass = ""; $db_name = "blog_login"; $conn = mysql_connect($dbhost, $dbusername, $dbpass) or die("Cannot connect to MySQL database server:".mysql_error()); $db = mysql_select_db($db_name, $conn) or die("Cannot open database:".mysql_error($conn));

E. Creating a database table:

CREATE TABLE IF NOT EXISTS `zip_city` (`id` int(11) NOT NULL AUTO_INCREMENT, `zip` varchar(5) NOT NULL, `city` varchar(255) NOT NULL, `country` varchar(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=41921 ;

  • you can auto-substitute in the input field;

Some fields require a limited set of input values. For example, a user can enter two characters, see a list of countries that begin with these letters, and easily select the one they need. In addition, he certainly will not make mistakes in the name of his homeland. AJAX Auto-Complete under jQuery.

A. Connect in ‹header›:

1. jQuery library.
2. Autocomplete script for jQuery.
3. Main script.

B. The HTML code of the form is as follows:

A country

1. The field in which you need to start entering the name of the country.

V.init.js:

Var options, a; jQuery(function())( options = ( serviceUrl:"./php/autocomplete.php" ); /*specify the address of the handler file*/ a = $("#query").autocomplete(options); /*assign autocomplete object with id="query"*/ ));

D. autocomplete.php: ajax request handler

If(isset($_GET["query"]) && (!empty($_GET["query"])))( require_once("db.php"); $db_table = "system_countries"; //database table name $ query = $_GET["query"]; //query from a form field $variants = ""; $q = "SELECT `name_en` FROM `($db_table)` WHERE `name_en` REGEXP "^($query)(. *)" GROUP BY `name_en`"; /*search by the first characters entered*/ $res = mysql_query($q) or die("Cannot run query:Query: ".$q."".mysql_error($conn) ); /*get the query result*/ if(mysql_num_rows($res)>0)( while($row = mysql_fetch_row($res))( $variants = """.$row."""; /*fill the array options*/ ) $variants = implode(",",$variants); /*type all options separated by commas into a line*/ /*form the answer*/ $request = "( query:"".$query."", suggestions:[".$variants."] )"; echo $request; ) )

D. Creating a database table:

DROP TABLE IF EXISTS `system_countries`; CREATE TABLE `system_countries` (`id` int(11) NOT NULL auto_increment, `name_en` char(128) NOT NULL, `name_ru` char(128) default NULL, `code` char(2) NOT NULL, `_order` int(3) default "0", `independent` tinyint(1) default "1", PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;

G. styles.css:

Autocomplete-w1 ( background:url(/autocomplete/img/shadow.png) no-repeat bottom right; position:absolute; top:0px; left:0px; margin:8px 0 0 6px; /* IE6 fix: */ _background :none; _margin:0; ) .autocomplete ( border:1px solid #999; background:#FFF; cursor:default; text-align:left; max-height:350px; overflow:auto; margin:-6px 6px 6px - 6px; /* IE6 specific: */ _height:350px; _margin:0; _overflow-x:hidden; ) .autocomplete .selected ( background:#F0F0F0; ) .autocomplete div ( padding:2px 5px; white-space:nowrap; ) .autocomplete strong ( font-weight:normal; color:#3399FF; )

  • Why enter data twice?

Many online stores use multi-step order forms with fields for payment and delivery addresses. Often their meanings are the same. Why not offer the user to duplicate the values ​​of already entered fields in one click? The technique is simple in software and you can use it in different cases, where the probability of repetition of values ​​is implied.

A. Connect in ‹header›:

1.JQuery library.

2. jQuery Select Plugin.

3. main script.

B. The HTML code of the forms is as follows:

First Name: Last Name: Email: Country: Select USA Canada Copy Delivery Details First Name: Last Name: Email: Country: Select US Canada

Payment details.

14. Copy checkbox.

V.init.js:

//when the page is loaded $(document).ready(function() ( //when the checkbox is activated or deactivated $("#copyaddress").click(function() ( // if activated if ($("#copyaddress") .is(":checked")) ( //for each input field $("#shipping_fields input", ":visible", document.body).each(function(i) ( //copying values ​​from payment fields // to the corresponding delivery fields $(this).val($("#billing_fields input").eq(i).val()); )); //does not work with drop-down menus, so we will use the plugin functions var bcountry = $( "#bcountry").val(); $("#scountry").selectOptions(bcountry); ) else ( //if the checkbox is deactivated //for each input field $("#shipping_fields input", ":visible", document.body).each(function(i) ( //clear delivery data fields $(this).val(""); )); $("#scountry").selectOptions(""); ) )) ; ));

  • It seems people are tired of reading captcha :)

You yourself are probably tired of reading illegible characters from the captcha and then entering them. Let's have mercy on users, but let's not let bots through. To do this, you can resort to several techniques, let’s consider one of them. Honeypot Captcha approach - we create a field on the form that is invisible to the user, but visible to the bot. By checking this value, we can catch careless spammers without creating difficulties for Real People. The impact of captcha on the conversion rate.

A. The HTML code for the form is as follows:

First Name Last Name E-Mail Hidden field. If you filled it out, then you are a bot

B. add the following js:

Function check() ( if(document.form_find.body.value)( console.log("CAUTION!!! BOT ON PAGE!!!"); ) )

Simplifying authorization forms

The authorization process is, figuratively speaking, when a person “says hello” to the site. In the Middle Ages, people in decent houses greeted people with multiple bows and curtsies. But we will keep up with the times and make sure that just one warm handshake is enough for a greeting. We make it easier to log into the site.

  • We leave the user on the page where he logged in;

There are two options to choose from: drop-down form and modal window. The drop-down form takes up only a small area of ​​the page, an easy and quick option to use.

A. We include libraries in the ‹header›:

3. Main script.

B. The HTML code of the form is as follows:

Login Password Remember me To authorize, enter your login: login and password: password

4. Button to open the form.

7-22. The form itself.

19. A checkbox that forces cookies to be installed for a very long time.

23. Place for message.

V. jqeasy.dropdown.js:

$(document).ready(function() ( /*main function*/ $(".btnsignin").click(function(e) ( /*when the "Login" button is clicked*/ e.preventDefault(); $ ("#frmsignin").toggle("fast",function() ( /*toggles the visibility of the form*/ $("#username").focus(); /*moves the input cursor to the login field*/ )); $ (this).toggleClass("btnsigninon"); /*toggles the class on the button to change the view*/ $("#msg").empty(); )); $(".btnsignin").mouseup(function() ( return false; )); $(document).mouseup(function(e) ( /*when the mouse is released*/ if($(e.target).parents("#frmsignin").length==0) ( / *not on one of the form objects*/ $(".btnsignin").removeClass("btnsigninon"); /*remove the form and return it as it was*/ $("#frmsignin").hide("fast"); ) ; )); $("#signin").ajaxForm(( beforeSubmit: validate, /*check first*/ success: function(data) ( /*when receiving a response from the handler*/ if (data=="OK") ( /*if it arrived OK*/ $("#frmsignin").text("Signed in!"); /*send a text notification*/ $("#frmsignin").delay(800).fadeOut(400); $("#signbtn").html("Exit"); /*change the exit button*/ ) else ( $("#msg").html(data); $("#username").focus(); ) ) )); )); function validate(formData, jqForm, options) ( /*validation procedure for entered data, contains error output processing*/ var form = jqForm; var un = $.trim(form.username.value); var pw = $.trim(form .password.value); var unReg = /^(3,20)$/; var pwReg = /^(6,20)$/; var hasError = false; var errmsg = ""; if (!un) ( errmsg = "Enter your login:

"; hasError = true; ) else if(!unReg.test(un)) ( errmsg = " Login must be 3 - 20 characters long (a-z, 0-9, _). "; hasError = true; ) if (! pw) ( errmsg += "Enter your password"; hasError = true; ) else if(!pwReg.test(pw)) ( errmsg += " Password must be 6 - 20 characters long (a-z, 0-9, !, @ , #, $, %, &, *, (,), _). "; hasError = true; ) if (!hasError) ( $("#msg").html(" request... "); ) else ( $("#msg").html(errmsg); return false; ) )

G. dropdown.php:

If(($_POST["username"]=="login") && ($_POST["password"]=="password"))( echo "OK"; )else( echo "Invalid login or password"; )

D. style.css:

Body( padding:20px; font:12px Verdana, Geneva, sans-serif; color:#333; ) #container ( width:700px; /*margin:0 auto;*/ padding:13px 10px; border:1px solid #999 ; ) a.btnsignin, a.btnsignout ( background:#999; padding:5px 8px; color:#fff; text-decoration:none; font-weight:bold; -webkit-border-radius:4px; -moz-border -radius:4px; border-radius:4px; ) a.btnsignin:hover, a.btnsignout:hover ( background:#666; ) a.btnsigninon ( background:#ccc!important; color:#666!important; outline: none; ) #frmsignin ( display:none; background-color:#ccc; position:absolute; top: 89px; width:215px; padding:12px; *margin-top: 5px; font-size:11px; -moz-border -radius:5px; -moz-border-radius-topleft:0; -webkit-border-radius:5px; -webkit-border-top-left-radius:0; border-radius:5px; border-top-left- radius:0; z-index:100; ) #frmsignin input, #frmsignin input ( display:block; -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; border:1px solid #666;margin:0 0 5px; padding:5px; width:203px; ) #frmsignin p ( margin:0; ) #frmsignin label ( font-weight:normal; ) #submitbtn ( -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; background- color:#333; border:1px solid #fff; color:#fff; padding:5px 8px; margin:0 5px 0 0; font-weight:bold; ) #submitbtn:hover, #submitbtn:focus ( border:1px solid #000; cursor:pointer; ) .submit ( padding-top:5px; ) #msg ( color:#F00; ) #msg img ( margin-bottom:-3px; ) #msg p ( margin:5px 0; ) # msg p:last-child ( margin-bottom:0px; ) h1( margin:0 auto; )

A modal window concentrates all attention on itself and at the same time allows you to place on the form Additional information or description.

A. We include libraries in the ‹header›:

4. Main script.

6. Basic styles.

7. Basic styles for the modal window.

B. The HTML code of the form is as follows:

Login | Personal Area Login Email Password Treatment...

2. Button to open the form.

6-27. Modal window.

8-11. Title of the modal window.

V.init.js:

// Preload img1 = new Image(16, 16); img1.src="./img/spinner.gif"; img2 = new Image(220, 19); img2.src="./img/ajax-loader.gif"; // When the DOM is ready $(document).ready(function())( // Launch MODAL BOX if the login link is clicked $("#login_link").click(function())( $("#login_form").modal() ; )); // When the form is submitted $("#status > form").submit(function())( // Hide the "Submit" button $("#submit").hide(); // Show a spinning gif $ ("#ajax_loading").show(); // "this" refers to the submitted form var str = $(this).serialize(); // -- Start AJAX call -- $.ajax(( type: "POST ", url: "php/do-login.php", // Authorization information is sent here data: str, success: function(msg)( $("#status").ajaxComplete(function(event, request, settings)( // Show the "Submit" button $("#submit").show(); // Hide the spinning gif $("#ajax_loading").hide(); if(msg == "OK") // LOGIN OK? ( var login_response = " " + " " + " " + " " + " " + " "+ "You have successfully logged in! Please wait for redirect... "; $("a.modalCloseImg").hide(); $("#simplemodal-container").css("width","500px"); $("#simplemodal-container ").css("height","120px"); $(this).html(login_response); // Refers to "status" // After 3 seconds, redirect setTimeout("go_to_private_page()", 3000); ) else // error? ( var login_response = msg; $("#login_response").html(login_response); ) )); ) )); // -- End of AJAX call -- return false; )); )); function go_to_private_page() ( window.location = "php/private.php"; // User's personal page )

G. do-login.php: ajax request handler

$config = array(); $config["email"] = " [email protected]"; $config["password"] = "demo123"; error_reporting(E_ALL ^ ​​E_NOTICE); //display all errors except notice // Session initialization session_id(); session_start(); header("Cache-control: private" ); // IE 6 FIX if($_POST["action"] == "user_login") ( $post_email = $_POST["email"]; $post_password = $_POST["password"]; // check the login and password if($post_email == $config["email"] && $post_password == $config["password"]) ( // Is everything correct? Register the session and redirect the user to his "Personal Account" $username = $post_email; $_SESSION["username"] = $username; if($_POST["remember_me"]) ( // set cookies for a month setcookie ("remember_me", true, (time() + TIME_DIFF) + (3600 * 24 * 30 )); setcookie ("info", $user_id.",".md5($password), (time() + TIME_DIFF) + (3600 * 24 * 30)); ) echo "OK"; // send success response for "init.js" ) else ( $auth_error = "Authorization data is incorrect."; echo $auth_error; ) )

D. private.php: a page that can only be accessed after authorization.

Include "config.php";//if there are appropriate cookies, then a session is established that the user is authorized // Checking whether the user is authorized if(!isSet($_SESSION["username"])) ( header("Location: /modal .html"); exit; ) echo "Personal page Hello, "; echo $_SESSION["username"]." | Exit This is your personal page ";

D.config.php:

Error_reporting(E_ALL ^ ​​E_NOTICE); session_start(); // Start the session header("Cache-control: private"); // IE 6 FIX // always modified header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // HTTP/1.1 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.0 header("Pragma: no-cache"); // ---------- LOGIN INFO ---------- // $config_username = "demo"; $config_password = "demo123"; $cookie_name = "siteAuth"; $cookie_time = (3600 * 24 * 30); // 30 days if(!$_SESSION["username"]) ( include_once "autologin.php"; )

E. autologin.php:

If(isSet($cookie_name)) ( // Check if the cookie exists if(isSet($_COOKIE[$cookie_name])) ( parse_str($_COOKIE[$cookie_name]); // Make a verification if(($usr = = $config_username) && ($hash == md5($config_password))) ( // Register the session $_SESSION["username"] = $config_username; ) ) )

Z. logout.php:

Include "config.php"; if(isSet($_SESSION["username"])) ( unset($_SESSION["username"]); if(isSet($_COOKIE[$cookie_name])) ( // remove "site_auth" cookie setcookie ($cookie_name, "", time() - $cookie_time); ) header("Location: modal.html"); exit; )

K. stylesheet.css:

Html, body ( padding: 0; border: 0px none; font-family: Verdana; font-size: 11px; ) /* Label */ label ( width: 80px; padding-left: 20px; margin: 5px; float: left ; text-align: left; ) /* Input text */ input ( margin: 5px; padding: 0px; float: left; border: 1px solid #cdcdcd; background-color: white; -moz-border-radius: 2px; ) br ( clear: left; ) .textbox ( border: 1px solid #999999; border-top-color: #CCCCCC; border-left-color: #CCCCCC; color: #333333; font: 90% Verdana, Helvetica, Arial , sans-serif; font-size: 11px; ) h1 ( font-size: 17px; ) div ( font-family: Verdana; font-size: 11px; ) /* "Login" Button */ #submit ( margin: 5px ; padding: 0px; float: left; width: 50px; background-color: white; ) #notification_error ( color: red; height: auto; padding: 4px; text-align: center; ) #login_response ( overflow: auto; ) #ajax_loading ( display: none; font-size: 12px; font-family: Tahoma; ) #logged_in ( padding: 5px; margin: 23px 0 100px 43px; padding: 5px; text-align: center; width: 400px; ) #status ( margin-top: 20px; width: 310px; )

L. basic.css:

/* Overlay */ #simplemodal-overlay (background-color:#aaaaaa; cursor:wait;) /* Container */ #simplemodal-container (height:180px; width:300px; background-color:#fff; border:1px solid #000000; -moz-border-radius: 5px; ) #simplemodal-container a.modalCloseImg (background:url("img/x.png") no-repeat; width:25px; height:29px; display:inline; z-index:3200; position:absolute; top:-15px; left:-18px; cursor:pointer;) #simplemodal-container #basicModalContent (padding:8px;)

  • Place the cursor in the first field of the form.

In order not to force the user to run his eyes and mouse around the page in search of a field where he needs to enter text, we can automatically place the cursor there. And the main thing is that it is done very simply, and they enjoy it.

A. The HTML code for the form is as follows:

Second field First field Third field

4. Focus B will be set to this field. Add the following js:

Function setFocus() ( /*set focus to the desired field*/ document.form_find.find_fio.select(); document.form_find.find_fio.focus(); )

Conclusion

Our goal is to make registration and login forms as nice and pleasant as, say, flight attendants. I hope my examples will be useful and will become the basis for creating your own masterpieces of form-building.

IN Twitter networks You can see the page working with a clean and simple design. Look at the right top part page, there you will see a button to log in to the system, by clicking on which you will see forms for filling out data. Today we will tell you how to create a similar effect on your own website. It's actually very simple. In addition, this will help you save space on the page and add a feeling of comfort to your visitors. In this article we will tell you step by step how this whole system works, and this guide will also be useful for those who want to learn jQuery. Forward!

HTML code

First you need to start with the HTML code. The HTML code is very simple - it contains the “a” tag, which goes along with the “fieldset” tag, due to which the form is displayed.

Just copy this into your code new page:


Have an account? Sign in


Username or email


Password




Remember me


Forgot your password?


Forgot your username?






CSS code

You will need using CSS to define the authorization button and login form. The code below performs exactly this function.

Just copy this code to your css file, or add it to the HTML code where you define the style. These codes define the login button.

#container (
width:780px;
margin:0 auto;
position: relative;
}

#content (
width:520px;
min-height:500px;
}
a:link, a:visited (
color:#27b;
text-decoration:none;
}
a:hover (
text-decoration:underline;
}
a img (
border-width:0;
}
#topnav (
padding:10px 0px 12px;
font-size:11px;
line-height:23px;
text-align:right;
}
#topnav a.signin (
background:#88bbd4;
padding:4px 6px 6px;
text-decoration:none;
font-weight:bold;
color:#fff;
-webkit-border-radius:4px;
-moz-border-radius:4px;
border-radius:4px;
*background:transparent url("images/signin-nav-bg-ie.png") no-repeat 0 0;
*padding:4px 12px 6px;
}
#topnav a.signin:hover (
background:#59B;
*background:transparent url("images/signin-nav-bg-hover-ie.png") no-repeat 0 0;
*padding:4px 12px 6px;
}
#topnav a.signin, #topnav a.signin:hover (
*background-position:0 3px!important;
}

a.signin(
position:relative;
margin-left:3px;
}
a.signin span(
background-image:url("images/toggle_down_light.png");
background-repeat:no-repeat;
background-position:100% 50%;
padding:4px 16px 6px 0;
}
#topnav a.menu-open (
background:#ddeef6!important;
color:#666!important;
outline:none;
}
#small_signup (
display:inline;
float:none;
line-height:23px;
margin:25px 0 0;
width:170px;
}
a.signin.menu-open span (
background-image:url("images/toggle_up_dark.png");
color:#789;
}

And then comes the definition of the login form:

#signin_menu (
-moz-border-radius-topleft:5px;
-moz-border-radius-bottomleft:5px;
-moz-border-radius-bottomright:5px;
-webkit-border-top-left-radius:5px;
-webkit-border-bottom-left-radius:5px;
-webkit-border-bottom-right-radius:5px;
display:none;
background-color:#ddeef6;
position:absolute;
width:210px;
z-index:100;
border:1px transparent;
text-align:left;
padding:12px;
top: 24.5px;
right: 0px;
margin-top:5px;
margin-right: 0px;
*margin-right: -1px;
color:#789;
font-size:11px;
}

#signin_menu input, #signin_menu input (
display:block;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border:1px solid #ACE;
font-size:13px;
margin:0 0 5px;
padding:5px;
width:203px;
}
#signin_menu p (
margin:0;
}
#signin_menu a (
color:#6AC;
}
#signin_menu label (
font-weight:normal;
}
#signin_menu p.remember (
padding:10px 0;
}
#signin_menu p.forgot, #signin_menu p.complete (
clear:both;
margin:5px 0;
}
#signin_menu p a (
color:#27B!important;
}
#signin_submit (
-moz-border-radius:4px;
-webkit-border-radius:4px;
background:#39d url("images/bg-btn-blue.png") repeat-x scroll 0 0;
border:1px solid #39D;
color:#fff;
text-shadow:0 -1px 0 #39d;
padding:4px 10px 5px;
font-size:11px;
margin:0 5px 0 0;
font-weight:bold;
}
#signin_submit::-moz-focus-inner (
padding:0;
border:0;
}
#signin_submit:hover, #signin_submit:focus (
background-position:0 -5px;
cursor:pointer;
}

It's time to work with javascript

It would seem that, HTML codes and CSS are quite complex and confusing, but in javascript everything is very simple. Just copy this javascript code, which will allow you to display and hide the form when you click on the login button, even if the click is made outside the login form.



$(document).ready(function() (

$(".signin").click(function(e) (
e.preventDefault();
$("fieldset#signin_menu").toggle();
$(".signin").toggleClass("menu-open");
});

$("fieldset#signin_menu").mouseup(function() (
return false
});
$(document).mouseup(function(e) (
if($(e.target).parent("a.signin").length==0) (
$(".signin").removeClass("menu-open");
$("fieldset#signin_menu").hide();
}
});

});

According to the code presented above, when a visitor clicks on the login button, the new feature. First, the login form is displayed (enclosed in the “filedset” tag), then the link, enclosed in the “.signin” class, adds another “menu-open” class, due to which the background image is changed.

Another event in this code is that when visitors click not on the login form, but somewhere on the page, the form closes itself. In other words, the "menu-open" class is stripped from the link with the ".signin" class and returns it to its original background image.

As for tips?


$(function() (
$("#forgot_username_link").tipsy((gravity: "w"));
});

We usually recommend using the jQuery plugin – tipsy. The content of the tooltip is what is written in the "title" attribute associated with the link. You can change the tooltip's position relative to east, west, south or north. This is implemented using the “gravity” parameter specified in the code above. We provide you with a link to a website dedicated to this plugin, where you can study its capabilities in more detail and download the plugin. ...

Finally

If you copied all the code from this article, please do not change the folder structure. If you change it, the code will not work. This code is just an example of creating a login dropdown form using jQuery. Good luck with your practice!

Everything runs under PHP and the data is stored in a MySQL database.

The system uses an excellent sliding panel developed by Web-kreation.

Step 1 - MySQL

First we need to create a table that will contain all the data about registered users. The query code is available in the table.sql file in the source archive.

table.sql --
-- Structure of the `tz_members` table
--
CREATE TABLE `tz_members` (
`id` int(11) NOT NULL auto_increment,
`usr` varchar(32) collate utf8_unicode_ci NOT NULL default "",
`pass` varchar(32) collate utf8_unicode_ci NOT NULL default "",
`email` varchar(255) collate utf8_unicode_ci NOT NULL default "",
`regIP` varchar(15) collate utf8_unicode_ci NOT NULL default "",
`dt` datetime NOT NULL default "0000-00-00 00:00:00",
PRIMARY KEY (`id`),
UNIQUE KEY `usr` (`usr`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

We define the id as an integer with the auto_increment option - it will be automatically assigned for each new registered user. Also, usr is defined as a unique key - two records with the same user name are not allowed to exist in the table.

Later we will use the specified properties during the registration process when the username is entered.

After creating the table, you need to fill in the variables for connecting to your database in the connect.php file so that you can run the code on your server.

Step 2 - XHTML

First, we need to embed a Web-creation form into our page.

demo.php




jQuery Sliding Panel
Solution for user registration/login to the site





Login for registered users

Username:

Password:

Remember me







Not registered yet? Enter your details!

Username:

Email:

The password will be sent to you by mail.





For registered users

Demo data


Go to user page

Logout










In several places in the code there are PHP statements that check whether $_SESSION["usr"] or $_SESSION["id"] is defined. They have true values only if the page visitor is a registered user, which allows us to show hidden content for registered visitors.

After the form we place the rest of the page content.




jQuery Sliding Panel
Easy registration management using PHP and jQuery


Some text...




There is nothing special in the code.

Step 3 - PHP

Now we will convert the form into a complete registration and login system. In order to solve the problem, you will need something other than regular PHP code. The entire code is divided into two parts.

If you plan to add something, it is best to divide everything into several separate files and turn them on as needed. This approach helps to develop large projects and at the same time reuse code in different parts of the site.

Here's how it's implemented here.

demo.php define("INCLUDE_CHECK",true);
require "connect.php";
require "functions.php";
// These two files can only be included if INCLUDE_CHECK is defined
session_name("tzLogin");
// Start the session
session_set_cookie_params(2*7*24*60*60);
// Defines the cookie's lifetime to be two weeks
session_start();
if($_SESSION["id"] && !isset($_COOKIE["tzRemember"]) && !$_SESSION["rememberMe"])
{
// If you are logged in but don't have the tzRemember cookie (browser restart)
// and you didn't check the Remember me checkbox:
$_SESSION = array();
session_destroy();
//Delete the session
}
if(isset($_GET["logoff"]))
{
$_SESSION = array();
session_destroy();
header("Location: demo.php");
exit;
}
if($_POST["submit"]=="Login")
{
// Check that the request came from the Login form
$err = array();
// Save the error
if(!$_POST["username"] || !$_POST["password"])
$err = "All fields must be filled in!";
if(!count($err))
{

$_POST["password"] = mysql_real_escape_string($_POST["password"]);
$_POST["rememberMe"] = (int)$_POST["rememberMe"];
// Prepare all data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr="($_POST["username"])" AND pass="".md5($_POST["password"]).""")) ;
if($row["usr"])
{
// If everything is in order, then log in
$_SESSION["usr"]=$row["usr"];
$_SESSION["id"] = $row["id"];
$_SESSION["rememberMe"] = $_POST["rememberMe"];
// Save some data in the session
setcookie("tzRemember",$_POST["rememberMe"]);
// Create the tzRemember cookie
}
else $err="Invalid username and/or password!";
}
if($err)
$_SESSION["msg"]["login-err"] = implode("
",$err);
// Save the error message in the session
header("Location: demo.php");
exit;
}

Here, the tzRemember cookie acts as a control element to determine whether to log out a user who has not checked the “Remember me” checkbox. If the cookie is missing (due to a browser restart) and the visitor did not check the “remember me” option, we delete the session.

The session itself will remain active for two weeks (as set in the session_set_cookie_params parameter).

And here is the second part of demo.php.

Else if($_POST["submit"]=="Register")
{
// If the request is sent from the Registration form
$err = array();
if(strlen($_POST["username"])32)
{
$err="Username must be between 3 and 32 characters long!";
}
if(preg_match("/[^a-z0-9\-\_\.]+/i",$_POST["username"]))
{
$err="The username contains invalid characters!";
}
if(!checkEmail($_POST["email"]))
{
$err="Your email address wrong!";
}
if(!count($err))
{
// If there are no errors
$pass = substr(md5($_SERVER["REMOTE_ADDR"].microtime().rand(1.100000)),0.6);
// Generate a random password
$_POST["email"] = mysql_real_escape_string($_POST["email"]);
$_POST["username"] = mysql_real_escape_string($_POST["username"]);
// prepare the data
mysql_query(" INSERT INTO tz_members(usr,pass,email,regIP,dt)
VALUES(
"".$_POST["username"]."",
"".md5($pass).",
"".$_POST["email"]."",
"".$_SERVER["REMOTE_ADDR"]."",
NOW()
)");
if(mysql_affected_rows($link)==1)
{
send_mail("demo-test@site",
$_POST["email"],
"Demonstration of the registration system - password generation",
"Your password: ".$pass);
$_SESSION["msg"]["reg-success"]="We have sent you an email with your new password!";
}
else $err="This username is already in use!";
}
if(count($err))
{
$_SESSION["msg"]["reg-err"] = implode("
",$err);
}
header("Location: demo.php");
exit;
}
$script = "";
if($_SESSION["msg"])
{
// The script shows a sliding panel on the loading page
$script = "

$(function())(
$("div#panel").show();
$("#toggle a").toggle();
});
";
}

We store all defined errors in the $err array, which is later assigned to the $_SESSION variable. This way, access to it is maintained after the browser is redirected.

Some sites may receive a warning when a form is submitted or the next time the page is refreshed that the data has already been submitted. This can be a problem, as it leads to duplicate registrations and unnecessary load on the server.

We use the header function to prevent an error by redirecting the browser to the same page. This updates the view of the page without the browser recognizing it as a form request. As a result, the page is refreshed and no data is transferred.

But since we are using $_SESSION to store all detected errors, it is very important that we reset all variables as soon as the error is shown to the user. Otherwise it will be displayed on every page view.

An additional script is also used that shows the panel on the loading page so that the message is visible to the user.


Step 4 - CSS

The sliding panel uses its own styles file. So all we have to do is create a style for our page.

demo.css body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label(
/* Reset rules */
margin:0px;
padding:0px;
}
body(
color:#555555;
font-size:13px;
background: #eeeeee;
font-family:Arial, Helvetica, sans-serif;
width: 100%;
}
h1(
font-size:28px;
font-weight:bold;
font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;
letter-spacing:1px;
}
h2(
font-family:"Arial Narrow",Arial,Helvetica,sans-serif;
font-size:10px;
font-weight:normal;
letter-spacing:1px;
padding-left:2px;
text-transform:uppercase;
white-space:wrap;
margin-top:4px;
color:#888888;
}
#main p(
padding-bottom:8px;
}
.clear(
clear:both;
}
#main(
width:800px;
/* Center in the middle of the page */
margin:60px auto;
}
.container(
margin-top:20px;
background:#FFFFFF;
border:1px solid #E0E0E0;
padding:15px;
/* Rounded corners */
-moz-border-radius:20px;
-khtml-border-radius: 20px;
-webkit-border-radius: 20px;
border-radius:20px;
}
.err(
color:red;
}
.success(
color:#00CC00;
}
a, a:visited (
color:#00BBFF;
text-decoration:none;
outline:none;
}
a:hover(
text-decoration:underline;
}
.tutorial-info(
text-align:center;
padding:10px;
) Step 5 - jQuery

The sliding panel has its own jQuery file.

demo.php






The first line includes the jQuery library from Google's CDN. Next comes an IE6 PNG patch for transparency elements. Then the panel script is turned on

The $script variable shows the panel on the loading page if necessary.

In this tutorial we will create a stylish authorization form on the site, you can find it in Futurico UI Pro, created by Vladimir Kudinov. We will use CSS3 and jQuery to create the form.

Step 1 - HTML Markup

Let's start by creating the HTML markup. Let's create a form with four inputs (username, password, checkbox and "submit" button) and wrap the checkbox in a span tag, which we will use to style this checkbox. Next, we'll wrap the form and title in a DIV tag and assign it the "login-form" class.

Login Form



remember

Step 2 - General Styles

First, let's remove all margins, padding, borders, etc. of the elements we will use.

Login-form
.login-form h1,
.login-form span,
.login-form input,
.login-form label (
margin: 0;
padding: 0;
border: 0;
outline: 0;
}

Next, let's set the styles for the form container. We'll add relative positioning, fixed width and height, background color, rounded corners, and shadows.

Login-form (
position: relative;
width: 200px;
height: 200px;
padding: 15px 25px 0 25px;
margin-top: 15px;
cursor: default;

background-color : #141517 ;

Webkit-border-radius: 5px ;
-moz-border-radius: 5px ;
border-radius: 5px ;

Webkit-box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .2) , inset 0px 1px 1px 0px rgb (0 , 0 , 0 ) ;
-moz-box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .2) , inset 0px 1px 1px 0px rgb (0 , 0 , 0 ) ;
box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .2) , inset 0px 1px 1px 0px rgb (0 , 0 , 0 ) ;
}

To create an arrow, we will use the :before selector.

Login-form :before (
position: absolute;
top: -12px;
left: 10px;

width: 0px;
height: 0px;
content : "" ;

border-bottom : 10px solid #141517 ;
border-right : 10px solid #141517 ;
border-top : 10px solid transparent ;
border-left : 10px solid transparent ;
}

Let's add some styles for the form header (color, font and size, etc.).

Login-form h1 (
line-height: 40px;
font-family : "Myriad Pro" , sans-serif ;
font-size: 22px;
font-weight: normal;
color : #e4e4e4 ;
}

Step 3 - General Styles for Form Fields

First, let's set the basic styles for the inputs.




line-height: 14px;
margin: 10px 0;
padding: 6px 15px;
border: 0;
outline: none;

font-family: Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
text-shadow : 0px 1px 1px rgba(255 , 255 , 255 , .2) ;

Webkit-border-radius: 26px ;
-moz-border-radius: 26px ;
border-radius: 26px ;

Webkit-transition: all .15s ease-in-out;
-moz-transition: all .15s ease-in-out;
-o-transition: all .15s ease-in-out;
transition: all .15s ease-in-out;
}

Then we will set styles for the login and password input fields. We'll add a gradient gray background and shadows. We will also add a fixed width of 170px and a color for the text.

Login-form input[ type= text ],
.login-form input[ type= password] ,
.js .login-form span (
color : #686868 ;
width: 170px;

Webkit-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) ;
-moz-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) ;
box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) ;

background : #989898 ;
background : -moz-linear-gradient(top , #ffffff 0% , #989898 100% ) ;
background : -webkit-gradient(linear, left top , left bottom , color-stop(0% , #ffffff ) , color-stop(100% , #989898 ) ) ;
background : -webkit-linear-gradient(top , #ffffff 0% , #989898 100% ) ;
background : -o-linear-gradient(top , #ffffff 0% , #989898 100% ) ;
background : -ms-linear-gradient(top , #ffffff 0% , #989898 100% ) ;
background : linear-gradient(top , #ffffff 0% , #989898 100% ) ;
}

When you hover your mouse over these fields, we will change their shadows.

Login-form input[ type= text ] :hover ,
.login-form input[ type= password] :hover (
-webkit-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) , 0px 0px 5px rgba(255 , 255 , 255 , .5) ;
-moz-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) , 0px 0px 5px rgba(255 , 255 , 255 , .5) ;
box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .6) , 0px 0px 5px rgba(255 , 255 , 255 , .5) ;
}

For the active state we'll change the CSS3 gradient to a slightly lighter color

Login-form input[ type= text ] :focus ,
.login-form input[ type= password] :focus (
background : #e1e1e1 ;
background : -moz-linear-gradient(top , #ffffff 0% , #e1e1e1 100% ) ;
background : -webkit-gradient(linear, left top , left bottom , color-stop(0% , #ffffff ) , color-stop(100% , #e1e1e1 ) ) ;
background : -webkit-linear-gradient(top , #ffffff 0% , #e1e1e1 100% ) ;
background : -o-linear-gradient(top , #ffffff 0% , #e1e1e1 100% ) ;
background : -ms-linear-gradient(top , #ffffff 0% , #e1e1e1 100% ) ;
background : linear-gradient(top , #ffffff 0% , #e1e1e1 100% ) ;
}

Step 4 - Submit Button

Let's place the button on the right; to do this, give it float:right.

Login-form input[ type= submit] (
float: right;
cursor: pointer;

color : #445b0f ;

Webkit-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .45) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
-moz-box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .45) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
box-shadow: inset 1px 1px 1px 0px rgba(255 , 255 , 255 , .45) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
}

When you hover the mouse, we will change the shadows, and in the active state, we will remove them.

Login-form input[ type= submit] :hover (
-webkit-box-shadow: inset 1px 1px 3px 0px rgba(255 , 255 , 255 , .8) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .6) ;
-moz-box-shadow: inset 1px 1px 3px 0px rgba(255 , 255 , 255 , .8) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .6) ;
box-shadow: inset 1px 1px 3px 0px rgba(255 , 255 , 255 , .8) , 0px 1px 1px 0px rgba(0 , 0 , 0 , .6) ;
}

Login-form input[ type= submit] :active (
-webkit-box-shadow: none ;
-moz-box-shadow: none ;
box-shadow: none ;
}

Let's add a green gradient for the button.

Login-form input[ type= submit] ,
.js .login-form span.checked :before (
background : #a5cd4e ;
background : -moz-linear-gradient(top , #a5cd4e 0% , #6b8f1a 100% ) ;
background : -webkit-gradient(linear, left top , left bottom , color-stop(0% , #a5cd4e ) , color-stop(100% , #6b8f1a ) ) ;
background : -webkit-linear-gradient(top , #a5cd4e 0% , #6b8f1a 100% ) ;
background : -o-linear-gradient(top , #a5cd4e 0% , #6b8f1a 100% ) ;
background : -ms-linear-gradient(top , #a5cd4e 0% , #6b8f1a 100% ) ;
background : linear-gradient(top , #a5cd4e 0% , #6b8f1a 100% ) ;
}

Step 5 - Style the Checkbox

Now comes the hard part because we can't change the appearance of the checkboxes with using CSS, just like we changed the appearance of other form fields.

The easiest way I found is to replace the checkbox with a span tag.

It will work like this: first we will hide the checkbox and style the span tag to make it look like a checkbox and then we will update that checkbox (checked/unchecked) using jQuery.

Since some users have JavaScript disabled, we need to add a fallback option. For this we will add "js" class in the body tag using jQuery. So, if JavaScript is enabled, the class "js" will be added to the body tag when the page loads, but if JavaScript is disabled, the class will not be added. So only JavaScript enabled users will see the styled checkbox.

First we will hide the checkbox.

.js .login-form input[ type= checkbox] (
position: fixed;
left: -9999px;
}

Then we will place the span tag where we need it.

.login-form span (
position: relative;
margin-top: 15px;
float: left;
}

Next, we'll add some styles to the span tag (width, height, border, etc.).

.js .login-form span (
width: 16px;
height: 16px;
cursor: pointer;

Webkit-border-radius: 2px ;
-moz-border-radius: 2px ;
border-radius: 2px ;
}

To create the "checked" state, we'll insert a small square into the span and place it in the center.

.js .login-form span.checked :before (
content : "" ;
position: absolute;
top: 4px;
left: 4px;
width: 8px;
height: 8px;

Webkit-box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .45) , inset 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
-moz-box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .45) , inset 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
box-shadow: 0px 1px 1px 0px rgba(255 , 255 , 255 , .45) , inset 0px 1px 1px 0px rgba(0 , 0 , 0 , .3) ;
}

We'll place the label tag to the right of the checkbox and add some basic styling (font, color, etc.).

.login-form label (
position: absolute;
top: 1px;
left: 25px;
font-family: sans-serif;
font-weight: bold;
font-size: 12px;
color : #e4e4e4 ;
}

All styles that have the class "js" at the beginning will only be applied if JavaScript is enabled.

Step 6 - jQuery

First we will connect latest version jQuery library using Google API, if you want you can host it on your own server, it's your choice. Then add the following code at the bottom of the HTML file, before the closing tag.

< script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" >
< script>
$(document).ready(function() (

// Check if JavaScript is enabled
$("body" ) .addClass ( "js" ) ;

// Make the checkbox checked on load
$(".login-form span" ) .addClass ( "checked" ) .children ( "input" ) .attr ( "checked" , true ) ;

// Click function
$(".login-form span" ) .on ("click" , function () (

if ($(this ) .children ("input" ) .attr ("checked" ) ) (
$(this) .children ("input" ) .attr ("checked" , false ) ;
$(this).removeClass("checked");
}

else(
$(this) .children ("input" ) .attr ("checked" , true ) ;
$(this).addClass("checked");
}
} ) ;
} ) ;

First we will add the "js" class to the body tag.


If you have any questions, we recommend using our forum to receive an answer as quickly as possible