Ajax login validation system in PHP using jQuery
- Thursday, April 24, 2008, 10:57
- ajax, jquery, php, tutorial
- 140 comments
Last time, I’ve showed you how to check user availability in Ajax using jQuery’s fading effect. But I’ve just shown the example without connecting the database and some people have faced problem with database connecting solution of that problem.In this post, I’ll show you how to use Ajax login system in php using jQuery and some animation as well.
In this example, first of all we’ll validate the user login detail from ajax showing the messages with some animation. If authenticated, the user will be redirected to the secure page “secure.php”. If you’ll try to directly access “secure.php”, you can’t do that.
Now let’s look at the code how to do this,
HTML Code
< form method="post" action="" id="login_form" /> < input name="username" type="text" id="username" value="" maxlength="20" /> < input name="password" type="password" id="password" value="" maxlength="20" /> < input name="Submit" type="submit" id="submit" value="Login" /> < /form >
As you can see in html code, we’ve created the form with id “login_form”.
And furthermore, the CSS code is same as the one available in the pervious post of checking user availability in ajax and php.
JavaScript Code for Ajax Login validation system in PHP
First of all we need to use the jQuery library in our code,
< script src="jquery.js" type="text/javascript" language="javascript"></script >
Now let’s look at the code in javaScript to call ajax and show the animated message with fading effects.
$("#login_form").submit(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//check the username exists or not from ajax
$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to secure page
document.location='secure.php';
});
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
});
}
});
return false;//not to post the form physically
});
As you can see above this code is preety much similar to the previous post of checking username availability in ajax and php and you can see the explanation of the above code from that post. But in above code, where the user is validated, he’ll be logged into the “secure.php” using “document.location” in JavaScript.
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
Well, as you can see above javaScript’s code, when focus is moved away from the password it also call the for sumit action. Basically whenever you hit tab button in password field, it starts validating the user detail using ajax.
PHP Code for Ajax Login validation system
First of all lets’s look at the code of the “ajax_login.php”.
//get the posted values
$user_name=htmlspecialchars($_POST['user_name'],ENT_QUOTES);
$pass=md5($_POST['password']);
//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
echo "yes";
//now set the session from here if needed
$_SESSION['u_name']=$user_name;
}
else
echo "no";
}
else
echo "no"; //Invalid Login
As you can see above, the user login detial is validated from the database. If the user login detail doesn’t exists, it just returns the “no” values and if the user login detial does exists the it just return “yes” values with setting username in session variable.
Finally, let’s look at the code of secure.php
if(empty($_SESSION['u_name']))
header("Location:index.html");
//if logout then destroy the session and redirect the user
if(isset($_GET['logout']))
{
session_destroy();
header("Location:index.html");
}
echo " <a href='secure.php?logout'><b>Logout<b></a> ";
echo " <div align='center'>You Are inside secured Page</a> ";
As you can see above the code of “secure.php” is simpleforward. If the user is not authenticated by session then he’ll be redirected to “index.html”. And there is link for “logout” in this page form where user can destroy the seession.
Implementation Guide:
To implement this code, dump the tbl_user “table” available in the zip file to your database and configure the database connection in “ajax_login.php”.
Popularity: 59% [?]
Related Posts
» Jquery : Benefits, Examples and Free Ebook
» jQuery is the most popular JavaScript and Ajax Framework
» Which is the best JavaScript and Ajax Framework ?
» Password protect a page using HTTP Authentication in PHP
140 Comments on “Ajax login validation system in PHP using jQuery”
Trackbacks
- Coding Nazi's - P2P Talk!
- Blog Pessoal de Filipe Veloza (YinYang)
- Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
- Login With PHP, MySQL, jQuery&Validation – ???????????????????? PHP |
- ??????? » [Web] ????
- pligg.com

I like your “error message” in the demo.
ha ha…..thanks gabe I always get bored with same stuffs and always try to do something new…so I got bored with old type of traditionl messages like “Invalid Login details”, so kept like that…
Another great tutorial! The files work here perfectly, however I do have a question:
The field name in the form , on index.html page, is called username.
In the ajax_login.php file, the values checked is user_name !
If I try the field name to user_name, then the script fails!
Can you explain that please?
thanks , Kamy
As you can see above javascript code, $.post(“ajax_login.php”,{ user_name:$(‘#username’).val(),password:
$(‘#password’)
Where the values of the element with id “username” is posted with the name of “user_name”. That where the confusion is.
Just change here as well..
Thanks! This was a great tutorial. I’ll be integrating this feature in my projects.
welcome kamy
This is nice, but it really breaks the back button, and is very unRESTful. I’m quite confident you can fix it to be both!
dear dale…I couldn’t get whare do you mean by “breaks back button”..can you please explain it ..so that I can fix the problem
how can i input other user user name and password in using logon system
I’m not clear with your question can you please clarify it…
Thank you for your email my question is when i open database the i see “d6dfb33a2052663df81c35e5496b3b1b” this pass word using “Admin” user so If i won’t to insart another user name and password then what can I do like if I wont to insart user Name “ranga” password like “229229″ i insart in database but it’s show error what can i do
well, password is stored in database using md5() has mechanism… so do echo md5(‘229229′); in php, that is the password to be stored in database.
OK I must be doing something wrong. The only thing I’ve done differently with your code is to put the form inside a div. When the user goes to an index page and clicks on a link, i load with form with a jquery command. Form loads fine. However, it seems as though the doc ready jquery stuff is not loading at all in the div – I even put an alert in right after the document.ready command and the alert does not display. If i continue to fill out the form and press submit, i’m just returned to my index page. Any idea what is going wrong?
I must have a feeling that you’ve error in javascript…try to open the page in internet explorer and check weather there is javascript error or not…and furthermore always put form tag outside the div which will ensure the proper DOM format.
Great script. Tho, after I’ve logged in I get this message -
“Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/xdxpnet/public_html/bjornis/secure.php:6) in /home/xdxpnet/public_html/bjornis/secure.php on line 180″
How to fix?
well…..sesssion_start() statement should be in the very first line of the page…
everything looks almost like it is working – one small issue. when i return from ajax_login.php, and the user has entered the correct userid and password (I’ve checked this writing this info to a log file) it seems as though the “yes” that is echoed in not being returned. As soon as I get to index.html, instead of “yes” being returned and the user logged in, the code executes at the else (not the if(data==’yes’) portion. Any idea why the correct info is not being returned via the ajax call?
I’m also having the same issue as Kathy. Everything works fine but the ‘yes’ response is not being recognized by the if(data == ‘yes’) even though Firebug shows the response is yes and if I display the “data” it prints out ‘yes’ but it will go directly to the “else” portion.
Thanks,
Allan
I think some space is there in the data value….try using if(jQuery.trim(data)==’yes’) , and hope this helps
Thanks! It works now!
Cheers,
Allan
thanks very much
Hi! I’ve just found your site and I’m loving it already!!!
I am stupid when it comes to Java and AJAX so I just have to ask you this: Can I hide all the javascript in the part of the idnex page like I could make a .css with the part? Can I do something as simple as putting all that JS inside the .js file or something like that?
Thanks in advanced!!!!
hi cesar..thanks for appreciation but I’ve not clear with your question but obviously you can put all the js code of one file and append them to another page but make sure that function and sequence of code are regular….
Thanks Roshan! You’ve got it. I want to show a more “clear code” to any user that right-click on my page and choose “View Source Code” and this should do it. I just didn’t understand why is that code not inside a .js file!
No it is just a small piece of code based on the jquery framework, so I didn’t put that inside the file of jquery, that’s all…yes for clear code you can put it inside a js file…it’s just demo tutorial not a professional development
I like it dude.. thX..
but this blog has a lot of Ajax code but nor used in this Blog.. like the e-mail checking in this damn comment.. so remember to put some Ajax here… or you lose some fun..and say that this code is’nt your or even maybe You Can’t Understand it…Yeb
ha ha…nice comment dude I like it..
It’s true that i’ve not given much time to improve the user interface of this blog due to my busy schedule and time constraints.I’m trying for this.
But not doing so doesn’t mean that it’s not my code. People come here in this blog to grab some useful code and how to implement it, they don’t care weather I’ve used Ajax in my comment system or not.
This code is great, i tried to change array to mysql. I have table name users and two column names (id, user_name).
I tried to write the code to check user name from mysql what I did was
$sql = “SELECT `user_name` FROM `users` WHERE `username` = ‘”$username”;
I’m not sure what to write next i really need your help please thanks.
AM
Hey are you trying ajax login system or you’re just trying to check username availability in ajax ..check this article
http://roshanbh.com.np/2008/04/check-username-available-ajax-php-jquery.html
I’m trying to check user name with database, using your code, but I’m having trouble to change from array to mysql database.
can you give me sample code to check user name from database.
for sample:
database name: members
column name is “Id, user_name”
i tried everything, but for some reason is not working. i would appreication if you can help me with mysql code to check user name please.
AM
Hello !
I tried the above example and it works well
when I use it on my local web server (localhost). But when I try to call a real domain (e.g. http://www.domain.com/login.php) it rises the “Permission denied” error when it tries to execute the xml.open method.
Is there something I misunderstood ? Could you please advice ?
it’s about the permission load all the files to server and access the file by removing http i.e. relative link..it will work
Hello !
It seems to work but only if the file is executed directly but not from the server localhost.
Could someone explain why xmlhttp object cannot call real domains from the localhost and is able to call directly ?
And another question : Could anybody advice why I am unable to perform a login on a real domain through ajax as the response received from the login page looks in the same way as in case of a wrong password (the name field keeps the name written inside and the password field is empty)
Could you please advice ?
Hello !
Thanks for your reply for the first comment. The problem is the domain is randomly selected, I am not the owner of it.
So, calling the file directly from my PC seems to work. The problem is the files are stored on my PC. I tried to call login page from a specific site and seems to work, but I have no confirmation the password is good or bad or another issue encountered.
Otherwise if a login directly from the owner’s site and then if I run my html file it seems the ajax response is different than when I try to login from my local page only and I can then obtain another information from that site.
XMLHTTP normally doesn’t allow you normally to access the files of another domain , it must be the same domain calling the script…
but you can check the following link for your cross-domain ajax problem
http://www.ajax-cross-domain.com/
this is cool – great code! i just have one problem – in secure.php, if the user logs in correctly, i reload index.php:
header(“Location:index.php”);
Then within index.php I have the following code so that if a user has logged in, they see additional navigation items. Even though it says the session has started, I’m not seeing the new items. Is the call to “header” destorying them? If so, how do I recall/reload the index.php page after successfull login?
Add News
View Data
I uploaded the files to my server. The login doesn’t work i did everything i needed to with the db but still fails! Please help!
Does the request is going to the PHP page ?
What is the response is coming from PHP page ?
no …. i downloaded the files as they were from ur site and added my db settings and inserted the table!
Too bad that if JavaScript is not turned on the validation won’t work at all. Otherwise pretty cool.
@Ticontster – If javascript is turned off then none of the javascript and ajax application works man
for more information how to handle them check this post
http://roshanbh.com.np/2008/04/how-to-know-handle-disabled-javascript.html
exelente tutorial felicitaciones.
pero me gustaria saber como puedo agregar un o varios texbox y usar el (plugin validate).
lo que quiero es implementar lo siguiente:
(“#login_form”) validate({
…
rules: {…},
messages: {…}
…
});
@Pedro – No he desarrollado un plugin este, esto es sólo una demostración de código así que me siento decir que no se puede aplicar esa norma en su aplicación.
Pero gracias por tu idea, voy a tener en cuenta para desarrollar ajax login plugin de jQuery
I don’t know spanish at all…but I’ve used Google Translation for this..howz it?
Creyo que google necesite unos classes de spanish pronto… <– That’s google talk lol
Que vivan los Ticos!
Gracias de todas maneras.
pero ya lo solucione.
(im understan Englihs but not speek and write good)
this is my solution using plugin validate of jquery (http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
espero les sirva de algo.
(es el mismo pero ahora valida los campos antes de enviar el formulario)
$(document).ready(function(){
$(“#formvalida”).validate({
rules:{ … },
messages:{ .. },
submitHandler: function(form){
$.post(“archivo.php”,
{ form_user:$(‘#form_user’).val(),
form_pass:$(‘#form_pass’).val(),
…
form_etc:$(‘#form_etc’).val(),function(data)
{ if(data==’0′) //if correct login detail
{ … }
else
{ … }
});
return false;
}
});
});
Hello, Roshan!
It is a great script and I would like to use it in my website.
But, I need to call the page “index.html” inside a DIV by an ajax. But it didn’t work even with scripts that allow to run javascript on it.
Could you help me.
Thanks a lot.
I’m back!
The problem is only on FF.
It works on IE7
Thanks
Roshan,
Thanks for the code. I have added the concept to a page where the user inserts their shipping details and assigns a Purchase Order number to their order. (Checking the availability of the PO number is where your code comes in).
Your code is situated within a DIV tag and works fine when the page first loads, but when the DIV tag is loaded using an AJAX event, the code no longer works.
I’ve done some searching around and have tried the bind function but can’t get it to work – I suspect I don’t have the bind function in the correct spot.
Any suggestions would be appreciated
I think there is problem with DOM elements of your page try to use the valid XHTML elements in your page and ajax page…
code is great but i want to keep user login in all pages. how to include some code which check r u login or not. thnkyou
@manpreet- you can use the following PHP code to check weather the user is logged in or not
if(empty($_SESSION['u_name']))
header(“Location:index.html”);
hi roshan when i am including this code in starting of every page
if(empty($_SESSION['u_name'])){
header(“Location:index.html”);
$ff = 1;
}
if(isset($_GET['logout']))
{echo $_GET['logout'];
session_destroy();
header(“Location:index.html”);}
then without login i cant enter to any page its sending back to index.html. but after lgin its working fine. wht i do so it can check properly.
Hi Roshan,
Is there are way i can add a “remember me” feature along with this? I attempted to add it to $.post but it just keeps on thinking the remember me radio button is ticked when it is not. How can i make it check if its ticked or not?
Thank You SO Much for this wonderful script.
@Ian- you can use cookie for adding remember me script….
@Ian- you can use cookie for adding remember me script….
But how do i set the cookie?
Because its ajax_login.php that sets the session, so i should be using it to set the cookie.
I used …
if($remember == “1″){
setcookie(“mPanelID”, $_SESSION['u_name'], time()+60*60*24*100, “/”);
}
$remember being $_POST[remember]
but it doesnt work!
Must i add remember:$(‘#remember’).val(), or something like that?
Hi!
Nice script there. I’m trying to use it in another Layout but I’m facing one problem:
The POST-Data is posted (according to FireBug) but when I print $_POST in ajax_login.php it’s empty! Therefore login always fails.
Any idea to that. Help is much appreciated!!!
THX in forward!
@Lukas…if the value is being posted but it’s not coming to the PHP page then there must be problem with the file name or path..please check the path once again..
@roshan
Thanks for the fast reply!
In the case you mention, the PHP Page wouldn’t answer right? But it does! Also FireBug would tell me. Any other idea?
Many thanks!
Hm.. Nice one, but don’t you think its dangerous to pass url of .php file in JavaScript so that everyone can see it from source? I’m talking about ajax_login.php ??
@pogran- As you know javascript code is visible with browser and in every ajax application you must pass the file name containing server side scripting so it doesn’t matter to pass the .php file name but you must account the security matter in that PHP file……
Yes, that’s right. JavaScript is what it is, but I meant dangerousness of using Ajax for login in general, not your solution..
For example if you use regular server-side method, you maybe won’t get so nice effect but so you don’t show file names to others.
In your script transaction of password to ajax_login.php is also not so perfect. Php file tells if it gets correct password for known username, all is needed for it is to create simple html page with correct input names and send with POST method..
Well, truly to say, I don’t see any progress of this but still I think its reasonable to add some more params by sending them to php file so that it would be harder to use it ‘from outside’!
@POGRAN – hello dude…..it’s not a professional solution and blog tutorial like only shows how to do the particular task simply and easily… it’s the part of users who have to add the security upto which extent do they need it.
Now another user may comment that it needs Captcha in the login form. It’s all your job dude to add the additional security.
And the method you’re talking about sending data via POST method is also not secure as it can be intruded with CSRF request.
Hi,
regarding Ian’s reply, is there anyway to add a ‘Remember Me’ Checkbox and feature to this login so that it the javascript checks if its ticked and posts it and if its not tick it wont post it. I know how to do the cookies and all, its the java side im having problems with, please help! thanks
@David- you can use two functions of javascript set and get the values from cookie of the link below.
http://www.w3schools.com/JS/js_cookies.asp
Hi Roshan! thanks for your great application. I am using this in conjunction with thickbox to make some really great forms on my website. One major problem I am having though, is passing a tag through the ajax.
i have:
Apple
Microsoft
Sony
Nintendo
have defined nptg:$(‘#nptg’).val()
but in my ajax.php file, $_POST['nptg'] returns undefined
any quick fixes? Again, thanks for the AWESOME work!
sorry! the comment system seems to eliminate my html.
i am using a select, drop down form element.
its name=nptg, and options are apple microsoft sony and nintendo.
Figured it out, in your select element you need an id=
Congratulations, a great script.
Please, two questions:
1 -How makes two checks on the same page?
$(document).ready(function() {
$(“#code”).blur(function()
});// end 1
$(document).ready(function() {
$(“#city”).blur(function()
});// end 2
2 – How to use two blur in the same check?
$(document).ready(function() {
$(“#city”).blur(function(); $(“#state”).blur(function()
});
Please help! thanks, Eusebio
@Eusebio – use this wasy
$(”#city #code”).blur(function()
and
$(”#city #state”).blur(function();
thanks… but it did not work
They are two different situations ..
First:
When there is any change in the two fields, only make a check.
//if the city is compatible with the state
$(”#city”).blur(function(); $(”#state”).blur(function()
$.post(“check_city_state.php
Second:
Two different checks to different fields, on the same page.
//if the NICK exist ??
$(document).ready(function() {
$(”#nick”).blur(function()
$.post(“check_nick.php
//if the EMAIL exist ??
$(document).ready(function() {
$(”#email”).blur(function()
$.post(“check_email.php
Sorry my english
thanks
this is really magnificent to login via ajax without reloading the page i like it
Hi Roshan
Your pages r cool. I have tested your nice login system little bit and i trying to get it work with thickbox. Login system working nicelly when i try it outside of thicbox, but when i opening login form to thickbox, then some reason i do not get return value of $.post() function. Or at least i look to be like that. Do you have any idea what i should try to get over this issue?
@Janne – which thickbox you’re using ? can you show me the link of thickbox u’re using ?
when i type the username and password it always says that your login detail sucks..
how can i fix it?
i dont know if my database connects… pls teach me how coz i’m a beginer in php and i want to learn because of my god damn thesis… pls help me mr. roshan…..
thanks a lot.. i hope you could help me….
ty.
Great post. I was struggling for a while trying to get it to work in my app but finally figured it out. I was encoding the file ajax_login.php with UTF-8 with BOM when I encoded in UTF-8 without BOM it worked
Hi Roshan,
I really like your code. Furthermore, If log in fail, i want to show message for a while only (5 seconds) then disappear message. What should i do with it?
Thanks in advanced.
Hi. Roshan, it is small great article…
I wondered to put the login form script in index.html into ajax_login.php
using this condition, if(data==’yes’) . it is doesn’t work. why? thank’s in advance
Great tutorial! But why the rand:Math.random() parameter?
Hi,
Great tutorial. I was wondering wthat the purpose of “math.random” is in this line:
$.post(“ajax_login.php”,{ user_name:$(‘#username’).val(),password:$(‘#password’).val(),rand:Math.random() } ,function(data)
{
Thanks,
Aman
Hi Roshan ,
Can you help me out ,using check user availablity in Ruby on Rails Apps .
Thanks in advance
Hi Rosham. Thanks for this excellent login system.
Unfortunatelly I can’t use it. If I put all files in my main localhost folder, it runs good, but if I move them to another directory, it doesn’t work.
It’s not problem about check permissions or the DB. I’ve tried to change this:
$.post(“ajax_login.php”
to this:
$.post(“admin/test/ajax_login.php”
but still doesn’t work.
Thanks for your help.
you don’t say exactly how to replace the password in the original zip.
If I wanted to have “user” as user name and “mypass” as the password, HOW CAN I DO IT?
I’ve tried everything: changing in the provided sql does not work, i’ve even tried to replace the $pass variable with a lame string ‘mypass’…it doesn’t work….nice tutorial, but incomplete
Hi,
Nice code,put remember me and forgot password option also.
hey, great work here mate.
Got a little problem tho. Im calling the app in a Fancybox and I cant see the errors inside it, seems like it will not validate before sending so to speak.
Hi Roshan,
I tried to view your demo and in case you don’t already know Google listed your site as suspicious.
Line from Google report:
Malicious software includes 62 exploit(s), 54 scripting exploit(s), 15 trojan(s). Successful infection resulted in an average of 36 new processes on the target machine.
I hope it’s nothing serious.
Simon
Hello Roshan
First I want to congratulate you for you blog.
Now my question: I’m doing a project where security is a BIG concern and when I try to see your demo I receive a page that tells me it’s dangerous and give this explanation:
http://safebrowsing.clients.google.com/safebrowsing/diagnostic?client=Firefox&hl=en-EN&site=http://roshanbh.com.np/examples/ajax-login-php
Is it true? If it’s true, how can this happen? Is this code vulnerable to code injection or what?
Thanks,
Anderson
hi anderson…….I had some problem with malware…now everything is alright…you can see the all of them again without any problem.
for preventing the response being cached. You can also use jquery’s ajax method and set the cache to false.
Nevermind! I figured it out! I had been echoing some debug info in my db-connection file and it was returning the debug info instead of YES. hahaha.
How can i do if i want to redirect to page with username?
document.location=’user.php?user=username’;
please help me out
Thank you Roshan! The script works like charm!
Work good, thanks…
Nevermind I fiqured it out, just had it redirect to my old login.php and used the session as the memid.
session_start();
session_register(‘frontuser’);
require_once(“config.php”);
require_once(“functions.php”);
$upmemid=$_SESSION['frontuser'];
if(isset($_GET['SQL2']))
{
$memid=str_replace(“‘”,”””,$_GET['SQL2']);
$namestr=fetchMember ($memid);
$namestr=split(“#”,$namestr);
$curbalance=$namestr[2];
}
I have a problem. When i input name nad password, the form submit when i click on page or if i clock on remember mi checkbox. Is it possible to submit the form only if i click submit button. Thank you for this great script.
First of all thanks a million for the script!!!!!!
Second please let me know how can i remove the message box after some time interval?
Thanks again and keep it up as we need them (the scripts offcourse)
!!!!!!!!!
How can i change the password and can i add more than one user?
development
testing
After validation I would like to redirect the page to development.html or testing.html based on the value of the selected radio button instead of secure.php
I can’t get the value of the radio button..any help?????
Hello Roshan,
I liked your work. But I don’t know where to place the username and password. Can I add more username and passwords for more members. Please help.
cool
great work, really appreciate for sharing your thoughts and ideas,
Hey guys,
If you need a complete login script with remember me and admin feautures try visting:
http://evolt.org/PHP-Login-System-with-Admin-Features
Though I recomend you are rather good at php and php classes. But its greatly made and I put this script together with the script from the link and it works like a breeze.
I also higly recommend to read and understand this.
Regards
Once again hi,
Regarding javascript disabled this can actually be solved verry verry easy in making a php switch one case with php validation and error messaging for javascript disabled and one without.
And for making the form work just type in the action of the file pointing to the php validation without java and then have javascript remove it. This way when javascript is disabled the form still submits and gives error messages.
Best regards
Hiya
Regarding timed events you might want to look in this:
http://jquery.offput.ca/timers/
Regards
IT’s is good example…
There is a error message in Safari. When i click on the username field, the browser gives an error and closes.
someone knows a solution?
Can you please incorporate remember me feauture into this login.
i want to add two columms to the database one called name and the other lastname.
when user log in i want to show the name and lastname of the user, how can i do that?
Regards
Hi one a problem.. in my host already eh created the data base with the necessary permissions but I cannot connect ..
[17-Aug-2009 06:36:33] PHP Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘mydomain_myuser’@'localhost’ (using password: YES) in /home/mydomain/public_html/demo/login_demo/ajax_login.php on line 4
technically it is the same code without altering, with the exception of the line where I put my user, password and data base to which one talks about.
Anyone out there with a similar script for registering new members?
@Tim:
http://evolt.org/PHP-Login-System-with-Admin-Features
Is difnately a site I’d recommend you to look and learn from. Though it requires you know how to code in classes but seriously this here is made with it all
Regards
Hi Roshan:
I’m back with a problem with this script….
I’ve loaded all the downloaded files as they were into my webserver.
Since my login system does not involve a mysql call (it gets done through API), I’ve removed all the code in the ajax_login.php file, except for testing purposes I kept the echo yes line.
I assumed ANY values entered in the login form would be acceptable that way, however the script still fails to accept the login.
Any ideas?
thanks in advance
Kamy
I have to furher add that there seems to be a bug in the files.
I’ve reinstalled all the files and used the proper mysql settings with the sql file that’s provided, and it still fails…..
PLEASE IGNORE MY LAST 2 POSTS!
The problem was totally on my end and the php session settings.
Really sorry!
thanks..great code….ur code is the only code i found in net for ajax login…which after validation takes to secure page…it will be much better if u can make it look like light box available in jquery….
sir wat to do if want to use it in my project plz help me out
hi
the code is working fine on my local wamp server! but it is not running in my webserver , when i uploaded in my website…it says ur login details sucks…i just changed my database settings, page layout..everthing is fine and working in my local server but not in webhosting’s server…plz help!! and can u provide me with code where i can enter series of user id and password…to allow multiplle user login???
Thanks Roshan! You’ve got it. I want to show a more “clear code” to any user that right-click on my page and choose “View Source Code” and this should do it. I just didn’t understand why is that code not inside a .js file!
Hi, I love this example, and have got it running on my mac under Mamp.
Just one question though:
How would I modify it so that each user that logs in is taken to a different secure page?
Thanks. Useful information.
great one … but can i use it with JSP rather than php ??
This is great. But as I understand AJAX is for changing sections of a page without having to resubmit the whole page. So instead of redirecting to secure.php, it could stay in the same index.html but on the top right cornor you could display the login information.. kind of like the information in Amazon. When you are redirecting the page I believe the whole point of AJAX is lost IMHO
Hi,
Great tutorial. Except there is a little bug. After I fill the boxes with something and hit submit, i receive the normal error message, but if I focus on password filed than on user name filed, the submit button triggers automatically. Hope you can fix that
Great job.
I found your articles is absolutely useful to me. But I wonder how to apply it into codeIgniter code.
It always stop at checking message box there but without post the username value to user_availability.php page. Any idea of that? Would you mind to show me how to do it? Will be appreciate if someone can help me with that. Thank you very very much.
Can this login code be altered to use a text file to store the username/password instead of a database
Hello Roshan,
Thx a lot for this code which would be very helpfull. However, I am unable to run your download code properly. The validation always fails and says that login detail sucks even when I try with the good login and password. Do you know how I can fix it? Thx for your help.
hello roshan,
your code looks great and simple,
i tried but some problem occured that i am unable to figure out, hope to get help from u
My probem is that whe i post the user name and password to ajax_login.php every thing woks fine and it also echoes “yes” but the data variable in the statement if(data==”yes”) in the javascript seems to be blank. when l console.log(“data:”+data) the value of the data in firebug i see that
data: is printed before “yes”
seems that my callback function is executed before the value passed is taken by the function….
some help would be appreciated..
Nice coding but I found a bug so u can try login thousands times with not your own username.
If you fill in an username and a password you can try to hack the account. If you only fill the username you can try hundreds of passwords. If you click on the username the errorbox refreshes everytime! Not a good login for evil hackers!
roshan do you have a solution for this?
Forgot the login form:
great work … I resolve my problema with your comment (jquery trim( ));
I don’t understand why you took the approach in first checking for the user and grab the row, then compare the password.
Why didn’t you just include the password in your SELECT query statement?
$sql=”SELECT user_name, password FROM tbl_user WHERE user_name=’”.$user_name.”‘ AND password = ‘.$password.’”;
This way you don’t need to return unnecessary result set all the time if an invalid password is provided.
Hi,
I will use it ,
thanks
I don’t know why, but the md5() function isn’t de-encrypting the password when I try this.
If I change line 34 on ‘ajax_login.php’ to: echo “rejected password =”.$pass;
And add the following line between lines 21 and 22 of ‘index.html’: alert(data);
I can see that the password is still very, very encoded and therefore fails the test.
I’m really curious why this is happening, if you have any ideas.
Thank you.
Yeah, so the only way I can get it to work is if I change line 27 of ‘ajax_login.php’ to:
if(strcmp($row['password'],$_POST['password'])==0)
Is this somehow risking the security of the site?
Great Script!
Any help to add the Remember Me checkbox will be welcomed
I tried to add it, but I am unable to even view if the checkbox is checked or not the ajax_login.php.
It is something stupid but I can’t find why I can’t see if it exist or not….
Any help will we be welcomed.
Thanks all and thanks for this great script