Ajax login validation system in PHP using jQuery

Advertisement

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.

View Demo

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.

Download Full Source Code

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”.

Tags: , ,

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

156 Comments on “Ajax login validation system in PHP using jQuery”

  • Gabe wrote on 24 April, 2008, 11:16

    I like your “error message” in the demo.

  • Roshan wrote on 24 April, 2008, 15:41

    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…

  • Kamy wrote on 24 April, 2008, 16:25

    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

  • Roshan wrote on 24 April, 2008, 16:33

    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..

  • Kamy wrote on 24 April, 2008, 18:06

    Thanks! This was a great tutorial. I’ll be integrating this feature in my projects.

    :)

  • Roshan wrote on 24 April, 2008, 18:08

    welcome kamy

  • Dale wrote on 25 April, 2008, 3:04

    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!

  • Roshan wrote on 25 April, 2008, 5:15

    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

  • Ranga Sarker wrote on 30 April, 2008, 8:02

    how can i input other user user name and password in using logon system

  • Roshan wrote on 30 April, 2008, 8:09

    I’m not clear with your question can you please clarify it…

  • Ranga Sarker wrote on 30 April, 2008, 8:16

    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

  • Roshan wrote on 30 April, 2008, 9:08

    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.

  • Kathy wrote on 4 May, 2008, 19:55

    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?

  • Roshan wrote on 5 May, 2008, 4:17

    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.

  • Pomba wrote on 6 May, 2008, 7:05

    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?

  • Roshan wrote on 6 May, 2008, 12:11

    well…..sesssion_start() statement should be in the very first line of the page…

  • Kathy wrote on 13 May, 2008, 0:00

    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?

  • Allan wrote on 14 May, 2008, 20:29

    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

  • Roshan wrote on 15 May, 2008, 9:08

    I think some space is there in the data value….try using if(jQuery.trim(data)==’yes’) , and hope this helps

  • Allan wrote on 15 May, 2008, 12:56

    Thanks! It works now!

    Cheers,
    Allan

  • ehab wrote on 16 May, 2008, 5:54

    thanks very much

  • Cesar wrote on 22 May, 2008, 13:35

    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!!!!

  • Roshan wrote on 22 May, 2008, 17:38

    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….

  • Cesar wrote on 22 May, 2008, 17:43

    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! :D

  • Roshan wrote on 23 May, 2008, 5:07

    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

  • AlGeRiA wrote on 25 May, 2008, 19:58

    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

  • Roshan wrote on 26 May, 2008, 4:30

    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.

  • Alidad wrote on 1 June, 2008, 17:37

    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

  • Roshan wrote on 1 June, 2008, 18:38

    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

  • Alidad wrote on 1 June, 2008, 18:44

    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

  • sovidiu wrote on 18 June, 2008, 10:03

    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 ?

  • Roshan wrote on 18 June, 2008, 10:27

    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

  • sovidiu wrote on 18 June, 2008, 10:39

    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 ?

  • sovidiu wrote on 18 June, 2008, 11:00

    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.

  • Roshan wrote on 18 June, 2008, 17:50

    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/

  • Kathy wrote on 21 June, 2008, 14:57

    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

  • Jake Parks wrote on 1 July, 2008, 17:44

    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!

  • Roshan wrote on 1 July, 2008, 17:53

    Does the request is going to the PHP page ?
    What is the response is coming from PHP page ?

  • Jake Parks wrote on 1 July, 2008, 18:03

    no …. i downloaded the files as they were from ur site and added my db settings and inserted the table!

  • Ticonetster wrote on 28 July, 2008, 5:19

    Too bad that if JavaScript is not turned on the validation won’t work at all. Otherwise pretty cool.

  • Roshan wrote on 28 July, 2008, 7:03

    @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

  • Pedro W. wrote on 28 July, 2008, 18:38

    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: {…}

    });

  • Roshan wrote on 29 July, 2008, 5:07

    @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?

  • Ticonetster wrote on 29 July, 2008, 12:53

    Creyo que google necesite unos classes de spanish pronto… <– That’s google talk lol

    Que vivan los Ticos! :)

  • Pedro W. wrote on 30 July, 2008, 1:56

    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;
    }
    });
    });

  • Thieberson wrote on 10 August, 2008, 14:06

    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.

  • Thieberson wrote on 10 August, 2008, 14:31

    I’m back!
    The problem is only on FF.
    It works on IE7

    Thanks

  • Paul Fleming McCullagh wrote on 11 August, 2008, 23:22

    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

  • Roshan wrote on 12 August, 2008, 17:20

    I think there is problem with DOM elements of your page try to use the valid XHTML elements in your page and ajax page…

  • manpreet wrote on 3 September, 2008, 13:58

    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

  • Roshan wrote on 3 September, 2008, 16:13

    @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”);

  • manpreet wrote on 3 September, 2008, 20:19

    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.

  • Ian wrote on 4 September, 2008, 19:51

    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.

  • Roshan wrote on 5 September, 2008, 8:43

    @Ian- you can use cookie for adding remember me script….

  • Ian wrote on 5 September, 2008, 10:23

    @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?

  • Lukas wrote on 9 September, 2008, 14:43

    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!

  • Roshan wrote on 9 September, 2008, 15:29

    @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..

  • Lukas wrote on 9 September, 2008, 19:03

    @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!

  • POGRAN wrote on 18 September, 2008, 4:12

    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 ??

  • Roshan wrote on 18 September, 2008, 4:19

    @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……

  • POGRAN wrote on 18 September, 2008, 5:50

    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’!

  • Roshan wrote on 18 September, 2008, 6:33

    @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.

  • David wrote on 19 September, 2008, 10:06

    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

  • Roshan wrote on 19 September, 2008, 10:37

    @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

  • Karl wrote on 19 September, 2008, 18:40

    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!

  • Karl wrote on 19 September, 2008, 18:41

    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.

  • Karl wrote on 19 September, 2008, 21:04

    Figured it out, in your select element you need an id=

  • Eusebio wrote on 25 September, 2008, 22:12

    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

  • Roshan wrote on 26 September, 2008, 4:31

    @Eusebio – use this wasy
    $(”#city #code”).blur(function()

    and

    $(”#city #state”).blur(function();

  • Eusebio wrote on 26 September, 2008, 12:45

    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

  • mahendra vala wrote on 23 October, 2008, 7:27

    this is really magnificent to login via ajax without reloading the page i like it

  • Janne wrote on 5 November, 2008, 23:20

    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?

  • Roshan wrote on 7 November, 2008, 5:36

    @Janne – which thickbox you’re using ? can you show me the link of thickbox u’re using ?

  • wako wrote on 30 November, 2008, 10:11

    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.

  • Sonny wrote on 11 December, 2008, 2:40

    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

  • veasna_set wrote on 18 December, 2008, 5:58

    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.

  • agus wrote on 26 December, 2008, 16:41

    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

  • Jesper wrote on 21 January, 2009, 18:12

    Great tutorial! But why the rand:Math.random() parameter?

  • Aman wrote on 25 January, 2009, 19:27

    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

  • John wrote on 30 January, 2009, 6:53

    Hi Roshan ,

    Can you help me out ,using check user availablity in Ruby on Rails Apps .
    Thanks in advance

  • Rafa Muñoz wrote on 31 January, 2009, 16:48

    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.

  • Cosmin wrote on 9 February, 2009, 23:40

    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 :|

  • svs wrote on 19 February, 2009, 10:38

    Hi,
    Nice code,put remember me and forgot password option also.

  • chris wrote on 5 March, 2009, 10:34

    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.

  • Simon wrote on 13 March, 2009, 1:26

    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

  • Anderson wrote on 15 March, 2009, 16:12

    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

  • Roshan wrote on 17 March, 2009, 9:42

    hi anderson…….I had some problem with malware…now everything is alright…you can see the all of them again without any problem.

  • Roshan wrote on 17 March, 2009, 13:49

    for preventing the response being cached. You can also use jquery’s ajax method and set the cache to false.

  • Mike wrote on 28 March, 2009, 16:48

    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.

  • Peter wrote on 28 March, 2009, 18:34

    How can i do if i want to redirect to page with username?
    document.location=’user.php?user=username';

    please help me out

  • Zheng Ji'an wrote on 30 March, 2009, 1:35

    Thank you Roshan! The script works like charm!

  • Daniel wrote on 6 April, 2009, 5:30

    Work good, thanks…

  • Julian wrote on 6 April, 2009, 14:54

    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];
    }

  • Alkin wrote on 16 April, 2009, 19:01

    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.

  • Antonis wrote on 20 May, 2009, 14:39

    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) ;) :)!!!!!!!!!

  • LGB wrote on 21 May, 2009, 18:44

    How can i change the password and can i add more than one user?

  • Anand Chhetri wrote on 26 May, 2009, 15:59

    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?????

  • Joble Jose wrote on 8 June, 2009, 1:36

    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.

  • xprycker wrote on 21 June, 2009, 10:22

    cool ;)

  • ?? wrote on 30 June, 2009, 2:51

    great work, really appreciate for sharing your thoughts and ideas,

  • Kasper wrote on 7 July, 2009, 1:06

    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

  • Kasper wrote on 8 July, 2009, 16:52

    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

  • Kasper wrote on 8 July, 2009, 17:37

    Hiya
    Regarding timed events you might want to look in this:
    http://jquery.offput.ca/timers/
    Regards

  • Deepak wrote on 14 July, 2009, 6:15

    IT’s is good example…

  • otto wrote on 22 July, 2009, 16:19

    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?

  • Deep Chandra wrote on 29 July, 2009, 9:50

    Can you please incorporate remember me feauture into this login.

  • Rodolfo wrote on 11 August, 2009, 16:24

    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

  • Luis wrote on 17 August, 2009, 12:57

    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.

  • Tim wrote on 18 August, 2009, 13:58

    Anyone out there with a similar script for registering new members?

  • Kasper wrote on 21 August, 2009, 10:43

    @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 :D

    Regards

  • Kamy wrote on 26 August, 2009, 18:51

    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

  • Kamy wrote on 26 August, 2009, 19:21

    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…..

  • Kamy wrote on 27 August, 2009, 14:34

    PLEASE IGNORE MY LAST 2 POSTS!

    The problem was totally on my end and the php session settings.

    Really sorry!

  • sweta wrote on 28 August, 2009, 9:04

    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….

  • zubair wrote on 29 August, 2009, 8:36

    sir wat to do if want to use it in my project plz help me out

  • sweta wrote on 29 August, 2009, 10:31

    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???

  • Bobr wrote on 30 August, 2009, 18:45

    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!

  • dmid wrote on 5 September, 2009, 13:38

    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?

  • Neutron wrote on 6 September, 2009, 10:25

    Thanks. Useful information.

  • asrar wrote on 11 September, 2009, 21:51

    great one … but can i use it with JSP rather than php ??

  • William Pitt wrote on 12 September, 2009, 16:13

    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

  • Andrei S wrote on 7 October, 2009, 12:05

    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.

  • huihui wrote on 19 October, 2009, 4:37

    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.

  • Shaka wrote on 30 October, 2009, 14:44

    Can this login code be altered to use a text file to store the username/password instead of a database

  • edi wrote on 10 November, 2009, 16:47

    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.

  • Gagan Shrestha wrote on 11 November, 2009, 3:11

    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..

  • Frank wrote on 16 November, 2009, 17:10

    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?

  • Frank wrote on 16 November, 2009, 17:43

    Forgot the login form:

  • paskuale wrote on 24 November, 2009, 8:45

    great work … I resolve my problema with your comment (jquery trim( ));

  • Kit wrote on 11 December, 2009, 8:35

    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.

  • MeD wrote on 11 December, 2009, 18:26

    Hi,
    I will use it ,
    thanks

  • tugboat wrote on 22 January, 2010, 17:17

    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.

  • tugboat wrote on 22 January, 2010, 17:37

    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?

  • Lionel wrote on 23 January, 2010, 20:53

    Great Script!

    Any help to add the Remember Me checkbox will be welcomed :D

    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

  • sHWETA wrote on 24 February, 2010, 4:43

    gr8 tutorial.thanx……………….

  • shweta wrote on 24 February, 2010, 10:02

    values r not posting on page.there is some problem with input field nmaes.can u plz sort it out

  • Nishant wrote on 25 February, 2010, 12:42

    Ur example is superb.. n i m using it in my application.. but for security issue.. i m facing a problem..
    i can see the username n password i send in firebug of firefox…. is there any way throw which i can hide it.. or encrypt it.?

    Thanks
    Nishant

  • Lars wrote on 23 March, 2010, 9:40

    I shamelessly stolen this and included it in my application, saved me surely atleast one hour of work. Thanks man!

  • Mattias Fjellvang wrote on 29 March, 2010, 19:18

    Ehm, delete this commment BUT… Could you edit my surname away? “Fjellvang”

    Only want it to say Mattias :-).

    Thanks.

  • Mattias Fjellvang wrote on 29 March, 2010, 19:24

    Hi. Me again, you can just delete all my comments, i found the problem in some of my PHP code, so had NOTHING to do with your script.

    Thanks anyways for a nice script!

  • DenW wrote on 3 April, 2010, 4:28

    Hi,

    I found your script searching for a login method using AJAX and tried it.
    Everything worked perfectly! Thanks for a great script..

    Yesterday however i decided to change jquery.js to an updated version (jquery-1.4.2-min.js).
    After uploading the new jquery, the login script isn’t working anymore. It simply does nothing (as far as i can tell) after i leave the password field.

    Would be great if you could fix this…

    Thanks for a great script!

  • Namet wrote on 9 April, 2010, 21:30

    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.

  • irmanator wrote on 20 April, 2010, 4:24

    Wow… simple, straight, and accurate!!!
    Thanks.

  • Martin wrote on 2 May, 2010, 11:58

    hI, thanks for your article but I’m having the same problem as a few people. The log in won’t work regardless of what I try. I read the comments and tried the trim but that doesn’t solve it either :(

  • Mattias wrote on 4 May, 2010, 6:22

    bah, comment system sucks :(.. i just entered a long reply for martin, but spam protection sum was wrong and now i need to rewrite everything.

    I make it short. check your ajax_login.php should only contain “yes” or “no” – NO other output like or no. And check if you connected to sql database/no php errors.

  • malaspigar wrote on 29 May, 2010, 16:03

    Hi,
    I don’t know who did this, but God bless you.
    You just solved a big problem. Thank you!

  • Peter wrote on 10 June, 2010, 7:26

    Hi Roshan, Great tutorial I am having one small problem though.

    I would like to insert my own username and password into the table but when I do this using the command,

    INSERT INTO `tbl_user` VALUES (1, ‘username’, ‘password’);

    It goes into the table fine but when I try to use the new username and password to log in it won’t let me through.

    Can you help?

    Thanks mate!

Trackbacks

  1. Coding Nazi's - P2P Talk!
  2. Blog Pessoal de Filipe Veloza (YinYang)
  3. Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
  4. Login With PHP, MySQL, jQuery&Validation – ???????????????????? PHP |
  5. ??????? » [Web] ????
  6. pligg.com
  7. You are now listed on FAQPAL
  8. Web Development, a Work in Progress « Neoxone
  9. Jquery13 is a place where designers and jquery developers can find very helpful plugins. » 5+ Fantastic jquery ajax login form
Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.