Ajax Jquery Login in PHP

Creating the Database

Create database “login” and create table “members” :

CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
);

INSERT INTO `members` VALUES (1, 'naveen', '123456');


main_login.php – file that will have the HTML form to get the username and the password from the user.
checklogin.php – our core file which will receive and send data from and to index.php
login_success.php -- Success message file after login successfully.
login.js – for our custom Jquery code for easy managemnt
jquery.min.js – we will download it from jquery website or we will directly use the link
style.css – place for basic style
Logout.php -- Logout file for logout purpose.


main_login.php

<div class=”loginform-in”>
<h1>User Login</h1>
<div class=”err” id=”add_err”></div>
<fieldset>
<form action=”checklogin.php” method=”post”>

<label for=”name”>Username </label>
<input type=”text” size=”30″ name=”name” id=”name” />
<label for=”name”>Password</label>
<input type=”password” size=”30″ name=”word” id=”word” />

<input type=”submit” id=”login” name=”login” value=”Login” class=”loginbutton” >

</form>
</fieldset>
</div>

I hope that the above code does not need any explanation. Its the form to gather username and password from the user. We move on to the next file.

checklogin.php

<?php
ob_start();
$host=”localhost”; // Host name
$username=”root”; // Mysql username
$password=”vertrigo”; // Mysql password
$db_name=”admin”; // Database name
$tbl_name=”members”; // Table name

// Connect to server and select databse.
mysql_connect(“$host”, “$username”, “$password”)or die(“cannot connect”);
mysql_select_db(“$db_name”)or die(“cannot select DB”);
$uName = $_POST[‘name’];
$pWord = $_POST[‘pwd’];
$qry = “SELECT username, password FROM members WHERE username='”.$uName.”‘ AND password='”.$pWord.”‘”;
$res = mysql_query($qry);
$num_row = mysql_num_rows($res);

if( $num_row == 1 ) {
echo ‘true’;
session_register(username);
session_register(password);

}
else {
echo ‘false’;
}
?>

receiving and assigning the values we gathered through the form in ‘main_login.php’.

The query which will help to retrieve user id, username, oauth and check if the username and the password entered does match with the stored data and if the user’s status field is set ‘active’ in the database. Then query execution, checking number of rows returned and fetching the resource from the above query execution.

Check if the number of rows is equal to 1. This is because there will be and should be only one user per login. If this condition is satisfied (true) then the next line is executed else it will return a ‘false’ to the Jquery script (we have not discussed about it till now. But will later…)

Assigning retrieved value from database to session for future use

login_success.php

<?php
// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
session_start();
if(!session_is_registered(username)){
header(“location:index.php”);
}
?>

<html>
<body>
Login Successful
</body>
</html>

 

Logout.php

<?php
session_start();
session_destroy();
?>

 

Proceeding to our next important file, ‘login.js‘ that will contain

$(document).ready(function(){
$(“#add_err”).css(‘display’, ‘none’, ‘important’);
$(“#login”).click(function(){
username=$(“#name”).val();
password=$(“#word”).val();
$.ajax({
type: “POST”,
url: “checklogin.php”,
data: “name=”+username+”&pwd=”+password,
success: function(html){
if(html==’true’) {
//$(“#add_err”).html(“right username or password”);
window.location=”login_success.php”;
}
else {
$(“#add_err”).css(‘display’, ‘inline’, ‘important’);
$(“#add_err”).html(“<img src=’images/alert.png’ />Wrong username or password”);
}
},
beforeSend:function()
{
$(“#add_err”).css(‘display’, ‘inline’, ‘important’);
$(“#add_err”).html(“<img src=’images/ajax-loader.gif’ /> Loading…”)
}
});
return false;
});
});

We are writing the above Jquery code goes in to ‘login.js’ file and the execution is started on document load (i hope you know the reason) but triggered when the ‘Submit’ button is clicked. In the further steps, the values from the input boxes are assigned to its variable and then call ajax for defining the form methods, the processing file URL (in this case, ‘login.php’ placed in the same directory) and finally, passing those assigned variable.

Now, handling the success or error feedback from ‘login.php’ file. On successful execution, we are redirecting the window to ‘dashboard.php’ and if the execution fails, we display an error message. But even before this success and error message handling, we display the ‘loading’ message in the same div with a simple loading gif image.

 

Note : Also include this link <script src=”http://code.jquery.com/jquery-1.10.2.min.js”></script>.

style.css, if you need it

.loginform-in {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #D6E5F5;
border-radius: 3px 3px 3px 3px;
height: 345px;
margin: auto;
padding: 0;
width: 460px;
}

.loginform-in fieldset {
border-bottom: 1px solid #EFEFEF;
margin: 20px auto;
padding: 0 0 10px;
width: 87%;
}

.loginbutton {
background: -moz-linear-gradient(center top , #F1F1F1, #E0E0E0) repeat scroll 0 0 transparent;
border: 1px solid #A7A7A7;
border-radius: 3px 3px 3px 3px;
color: #444444;
cursor: pointer;
font-family: “Helvetica Neue”;
font-size: 13px;
font-weight: normal;
height: 29px;
letter-spacing: 1px;
width: 92px;
}

.loginform-in fieldset label {
color: #7D7D7D;
float: left;
font-family: “Helvetica Neue”;
font-size: 14px;
font-weight: bold;
padding: 8px 0 0;
width: 140px;
}

.loginform-in fieldset input[type=”text”], input[type=”password”], fieldset select {
border: 1px solid #CBC7C5;
border-radius: 3px 3px 3px 3px;
float: left;
height: 33px;
padding: 1px 1px 1px 3px;
width: 250px;
}

 

This AJAX login form with Jquery and PHP is very basic but serves the purpose for small PHP applications. Since its an working example from a micro PHP application. You can even make this form more interesting by simply adding CSS and transition.
I prefer the ‘login.js’ to be added before the closing body tag but not the ‘jquery.js’.

I hope that this tutorial will be useful to you. If you have any doubt, do post them on the comment section.

And as usual, Thanks for reading,
Keep sharing.

 

 

  1. Lizhuzhubuun says:

    Dyson V6 Moor person Extras that each the actual models include apart from DYSON V6: Crevice resource. This is actually the the majority of ripped mouth limited suction nozzle, with regard to small 4 corners and splits. In my opinion, this is actually the lowest used program. Dyson V6 Fluffy Dissimilarities of Parts/Accessories Among the Types Selection of superior: DYSON V6 Pet animal. Truly Animal carries a higher original expense, however the lower price is big. Cost-performance good, it truly is associated with the guitar and guitar neck with the past suit. The total price is bigger because the whole set of most important suction leads are enhanced. Moreover, the actual name is Pet animal, it is really Powerful. Dyson V6 Absolute three or more. How to purchase a special model presenting the condition of my favorite house? (Personal point of view, for reference applications only) Dyson V6 Animal/Fluffy锛宼hey are usually pals that often reveal identical price tag Dyson V6 Trigger Products that the very models get but DYSON V6: Crevice resource. It is the most widespread ripped mouth shorter suction nozzle, for small 4 corners and cracks. In my experience, this is the the very least used tool. Personal choice of motor vehicle on-board/robot solution: Dyson V6 Result in + Mobile Suit, little but successful.

  2. Monicapa says:

    GIPSOKARTONA.COM – modern news resource . Breaking News Russia , US public news media format. Unique articles will help to experience the latest social problems and Hot новости Антимайдан and the world makes it possible to be aware of only the most sudbanosnyh and entertaining events. Also on our site you can explore Showbiz news , learn about the latest news curiosities and much more.
    GIPSOKARTONA.COM – social resource directory news Russia , laid out on a daily basis unusually fresh and File Holder selected topics. Included a lively discussion of all the news .Social interaction between people of the portal . Our journalists are trying to raise you up to date information and events 24 hours a day .

  3. Dell says:

    Very ggood post! We are linking to thos great articlke on our website.
    Keep up tthe great writing.

  4. That is a good tip especially to those fresh to the blogosphere.

    Brief but very accurate information… Thank you for sharing this
    one. A must read article!

  5. I just couldn’t depart your website before suggesting that I really enjoyed the usual
    information an individual supply in your guests? Is gonna be again regularly to inspect new posts

  6. Pretty nice post. I just stumbled upon your blog and wanted
    to mention that I have truly enjoyed surfing around your weblog posts.
    After all I’ll be subscribing on your rss feed and I’m hoping you write once more soon!

  7. This is very fascinating, You are an excessively professional blogger.
    I have joined your feed and sit up for in quest of
    more of your magnificent post. Additionally, I’ve shared your web site in my social networks

  8. In today’s realm of fashion, it usually is a privilege to become adorned with the stylish elements. Deloris begins, as a girl yearning one day so that it is big. Although they are expensive, some consumers still don’t adversity in regards to the price.
    http://karawickman.com/cartier_oatevd.karawickman.com/ http://karawickman.com/cartier_oatevd.karawickman.com/

  9. I was extremely pleased to find this great site.
    I need to to thank you for your time for this particularly fantastic read!!
    I definitely loved every bit of it and i also have you saved to
    fav to check out new information on your website.

  10. lovelonglong says:

    Just desire to say your article is as surprising.

    The clarity on your submit is simply great and i could assume you are an expert on this subject.
    Well with your permission allow me to grab your feed to stay up to date with
    coming near near post. Thanks 1,000,000 and please continue the rewarding work.

  11. Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me
    out much. I hope to give something back and help others like you aided
    me.

  12. Magnificent goods from you, man. I’ve understand your stuff previous to
    and you’re just extremely great. I really like what you have acquired
    here, really like what you’re saying and the way in which you say it.
    You make it entertaining and you still care for to keep it sensible.
    I cant wait to read far more from you. This is really a terrific site.

  13. Hey very cool website!! Guy .. Beautiful ..

    Wonderful .. I’ll bookmark your website and take the feeds also?

    I am happy to search out so many useful info right here within the submit, we need develop extra strategies in this regard, thanks for sharing.
    . . . . .

  14. Tiffany Cheap Fashion Jewelry & Denver colorado Outlet Jewelry Cheap Keep Discount Tiffany Jewelry seemed to be referred to as among the Plx1 causing kinases Cheap Tiffany Jewelry Qian avec ‘s.

  15. Great post but I was wondering if you could write a litte more on this subject?
    I’d be very thankful if you could elaborate a little bit more.

    Many thanks!

  16. Center simply is found a new rocks Nfl Cheap Jerseys place coming from Wholesale Nfl Jerseys the brand new residence. You may also brush-off the particular unfastened filth out of your furnishings often Nfl Jerseys From China.

  17. These kinds of trailers are available national football league junior tops affordable within programs and measurements. Therefore, it is possible to carry the help of a prominent dealer that will help you Cheap Nfl Jerseys work out which trailer home will be suitable p oker. Beamon Flick is probably the lowest priced nba cycling jerseys almost all typically discovered facets of visual relationship in contemporary tradition. low cost china cycling jerseys national hockey league Nas when compared to nrranmoins simples, temos other farol monoparbola, j nas sentiments prime, signifiant dupla parbola. Veja cual e logotipo da Volkswagen no encosta zero cap, ser zero caso conduct Playing golf brasileiro. Vincos na lataria faro do Novo Gol um hatch internet estilo minivan, parecido web i Peugeot 307. Peralta ended up being Detroits starting up shortstop, however the Lions obtained Jose Iglesias from Birkenstock boston before Peralta has been revoked following baseballs analysis straight into Biogenesis of America, some sort of California age reversing hospital charged with distributing banned effectiveness boosting drug treatments. The former Ohio State celeb which exclusively joined up with the Alouettes around September threw a couple of landing moves as part of his initially CFL start off because Montreal downed the particular Hamilton Tiger woods Cats Thirty-six Your five so that you can tighten the cheap blank cycling jerseys race intended for playoff positions on Wednesday morning. Low-cost nba nhl jerseys cina.

    PITTSBURGH Considerable demolition function has begun on the Social Arena, a igloo shaped former household in the Pittsburgh Penguins. The preservation party unsuccessful to use attempts to have process of law to hold your house out of remaining split down so that it may very well be remade. Upkeep Pittsburgh suggested the fact that flip-style metallic top around the 75 year-old constructing made nba nfl jerseys wholesale the far east it really worth salvaging. The Griffins located his or her dream dwelling. “I discovered that nba tops nike low-priced when I spotted an low-cost sewed nba jerseys tiongkok “Open House” indication as well as had taken a glance (for entertainment),Inch Laurie said. “I dragged Glenn here we are at view it a second time because I wished your pet actually low-cost nba tops to see the kind of home that I had want to live in one of these days if you meet the expense of it.Inches He enjoyed it, way too..

    Polo accounts so it continues to be notified which Laxey Partners Limited (“Laxey”) retains Five.04% of the voting protection under the law from the Company while at A pair of July The year 2010 and this Polo has brought your not for joining a measure provide letter (“Letter”) coming from Laxey. The Correspondence, which is susceptible to sufficient research and then any regulating ailments, claims that Laxey is thinking about generating a detailed discuss give to acquire the overall granted discuss money on the Organization through the special objective motor vehicle (“Offeror”) with consideration to get gives you from the Offeror. Your Offeror, which might be the shelling out organization for that reasons the AIM Rules, could subsequently sign up for get it’s given reveal investment capital said for you to exchanging in Strive.

    My family lifted me personally using “Beef Barg Kabob” and then for as much as From the Irrrve never actually viewed a menu with a Local eatery, since Wholesale Nfl Jerseys that is definitely almost all I actually obtained! I definitely hold the right to critique every “Barg Kabob” which chinese suppliers low cost tops u . s . has got actually existed on the face from the world because I i’m this King Associated with Barg Kabob! At this point, “Shamshiri’s” beef barg is over my personal number. Cardiovascular system involving Tenderloin that is certainly sliced up, skewered, marinated along with broiled, comes with brown rice and also prepared tomato plants can be perfectly soft. Get them having a facet of “Mast O’Moosir”, and that is perfectly sliced Shallots combined with solid Natural yogurt.. I am aware of myself personally in which because i still need 14 a lot more areas to travel, I must both return to the road or perhaps create long term dwelling low cost recreational softball cycling tops in the Blend Fry. It is just a tricky decision, on the other hand finally choose Cheap Nfl Nike Jerseys past. Pickle is their own situation.

  18. google says:

    Spot on with this write-up, I truly think this site needs a
    lot more attention. I’ll probably be returning to read through more, thanks for the advice!

  19. I seriously love your website.. Pleasant colors & theme. Did you develop this web site yourself?

    Please reply back as I’m wanting to create my own personal website and would love to learn where you got this from or exactly what the theme is named.Kudos!

  20. google says:

    Can I simply just say what a comfort to uncover someone who really understands what they are discussing on the internet.
    You certainly realize how to bring an issue to light and make it important.

    More and more people ought to read this and understand this side
    of your story. I can’t believe you aren’t more popular
    since you surely possess the gift.

  21. “Miss Tempest” was engaging and well-read, approved of my dual wishes to
    be a physician and writer as she spent an hour in the dining
    hall during a slack period, nursing cups of coffee and chatting with me about this and that.
    ‘Lifts: Passenger and Service lifts of suitable size and capacity in every block.
    “Mueller’s twin sons, Max and Bob, are being cared for by her mother in Palm Beach.

  22. Google says:

    My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on numerous websites for about a year and am concerned about
    switching to another platform. I have heard very good
    things about blogengine.net. Is there a way I can import all my wordpress content into it?

    Any kind of help would be really appreciated!

  23. May I simply just say what a comfort to discover someone that truly knows what they’re talking about on the web.
    You certainly understand how to bring a problem to light and make it important.
    More people should check this out and understand this side
    of your story. I was surprised you are not more popular because you most certainly
    possess the gift.

  24. App store is the hacker community standard cydia download free application store for Apple
    iOS devices such as the best paid cydia apps. On the right hand corner, you will seldom have to
    perform a soft reset every now and then. Enlisted
    below are some of the most to the least expensive option of repairing it yourself and regardless of what is broken in it, for when you upgrade, you lose the Cydia app.

  25. Howdy! I’m at work surfing around your blog from my new iphone!
    Just wanted to say I love reading through your blog and look forward to all your posts!
    Keep up the excellent work!

  26. How to Update Cydia for an iTouchCydia is a software application available for a jailbroken iPod
    Touch that allows you to add sources to Cydia in just a
    few ft. Looking to feed your download cydia iPhone, iPad or
    iPod Touch! Cydia, with more and more people resorting to this download cydia replacement software.

  27. NIKE Company. Low-cost Printed Tops Womens Ralph Lauren T Shirts Many people informed the criminals to choose some thing as well as Polo Electric outlet Cash flow a style, instead of entirely common.”. Servicing expenses aren a lot various inside most recent Lauren By Ralph Lauren Outlet diesels, or even Ron Lauren Polo Tees Inexpensive could they be more Inexpensive T-shirt harmful regarding preserve. “When Now i’m associated with a project, I supply my own, personal almost all Deprive Polo Ralph Lauren Outlet Online Shop Lauren Polo Apparel Outlet because of it,In . the specific controversial celeb explained.

  28. I think that is among the so much important info for me.
    And i am satisfied studying your article. However should commentary
    on few general issues, The site style is great, the articles is in point of fact nice : D.
    Just right process, cheers

  29. Casie says:

    What’s up colleagues, its impressive paragraph about tutoringand fully explained,
    keep it up all the time.

  30. Thanks for sharing your thoughts about casino bonus.
    Regards

  31. List.Ly says:

    When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each
    time a comment is added I get four emails with the same comment.
    Is there any way you can remove people from that service?
    Many thanks!

  32. List.Ly says:

    Can you tell us more about this? I’d care to find out more
    details.

  33. netticasino says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog
    that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience
    with something like this. Please let me know if you run into
    anything. I truly enjoy reading your blog and I look forward to your new updates.

  34. proxiesdudey says:

    Need new Proxies ? Here is your solution Proxy Raider the Nextgen Generation proxy scraper!
    Try the demo or get the fullversion at http://proxy-raider.com/ !

    Features:

    – Scanning of class A to C IP ranges for an unlimited amount of ports
    – Ability to scan each class C of a loaded IP list for additional proxies
    – Unique randomized IP generator to scan for proxies
    – Scraping of proxy IP’s from websites (proxy lists)
    – Search Engine Scraping of sites that list proxies (and extraction + verification of IPs in one process)
    – Heuristic scraping: de-obfuscation of proxy IP+port on websites that use javascript to hide the data
    – Javascript unpacker (sandboxed)
    – Verification of proxy lists against Google or custom sites
    – Verification of private proxy lists that require authentication
    – Ability to use internal proxies for scraping
    – Proxy type (Anonym/Transparent) and speed analysis
    – Internal GEO IP database
    – Multithreads (unlimited)
    – Pure sockets implementation, no insecure webbrowser controls
    – Blacklist of IP ranges to avoid (mostly .gov and .mil)
    + more!

    Proxy list

*