Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2010
    Posts
    99
    Thanks
    10
    Thanked 1 Time in 1 Post

    Implement ajax into existing php login?

    So confused. My current login system sends the user to a separate page if the login fails... its not very nice. So I have been trying to implement an ajax system using my existing login php, and I am not doing so well.

    My form will not submit, and when it does it still brings to user to a blank page. I cant figure it out, and it shouldnt be this hard. Can anyone take a minute and help my brain from exploding?

    My login form:
    Code:
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
    	
    	$("#submit").click(function() {
    	
    		var action = $("#loginform").attr('action');
    		var form_data = {
    			username: $("#login").val(),
    			password: $("#password").val(),
    			is_ajax: 1
    		};
    		
    		$.ajax({
    			type: "POST",
    			url: action,
    			data: form_data,
    			success: function(response)
    			{
    				if(response == 'success')
    					$("#loginform").slideUp('slow', function() {
    						$("#message").html("<p class='success'>You have logged in successfully!</p>");
    					});
    				else
    					$("#message").html("<p class='error'>Invalid username and/or password.</p>");	
    			}
    		});
    		
    		return false;
    	});
    	
    });
    </script>
    
    
    <form id="loginform" name="loginform" method="post" action="login-exec.php">
    
    <input name="login" type="text" class="textfield" id="login" onfocus="this.value=''" value="Email">
    <input name="password" type="password" class="textfield" id="password" onfocus="this.value=''" value="Password">
    
    <input type="submit" value="login" name="submit" id="submit">
    
    <div id="message"></div>
    </form>

    My php login:
    (I suspect this is maybe the problem because it was never meant to be handled by ajax?)
    PHP Code:
    <?php
        
    //Start session
        
    session_start();
        
        
    //Include database connection details
        
    require_once('../login/config.php');
        
        
    //Array to store validation errors
        
    $errmsg_arr = array();
        
        
    //Validation error flag
        
    $errflag false;
        
        
    //Connect to mysql server
        
    $link mysql_connect(DB_HOSTDB_USERDB_PASSWORD);
        if(!
    $link) {
            die(
    'Failed to connect to server: ' mysql_error());
        }
        
        
    //Select database
        
    $db mysql_select_db(DB_DATABASE);
        if(!
    $db) {
            die(
    "Unable to select database");
        }
        
        
    //Function to sanitize values received from the form. 
        
    function clean($str) {
            
    $str = @trim($str);
            if(
    get_magic_quotes_gpc()) {
                
    $str stripslashes($str);
            }
            return 
    mysql_real_escape_string($str);
        }
        
        
    //Sanitize the POST values
        
    $login clean($_POST['login']);
        
    $password clean($_POST['password']);
        
        
    //Input Validations
        
    if($login == '') {
            
    $errmsg_arr[] = 'Login ID missing';
            
    $errflag true;
        }
        if(
    $password == '') {
            
    $errmsg_arr[] = 'Password missing';
            
    $errflag true;
        }
        
        
    //If there are input validations, redirect back to the login form
        
    if($errflag) {
            
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            
    session_write_close();
            
    header("location: login-form.php");
            exit();
        }
        
        
    //Create query
        
    $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
        
    $result=mysql_query($qry);
        
        
    //Check whether the query was successful or not
        
    if($result) {
            if(
    mysql_num_rows($result) == 1) {
                
    //Login Successful
                
    session_regenerate_id();
                
    $member mysql_fetch_assoc($result);
                
    $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
                
    $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
                
    $_SESSION['SESS_LAST_NAME'] = $member['lastname'];
                
    session_write_close();
                
    header("location: ../home.php");
                exit();
            }else {
                
    //Login failed
                
    echo "Login error, please try again.";
                exit();
            }
        }else {
            die(
    "Query failed");
        }
    ?>

  • #2
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,313
    Thanks
    58
    Thanked 525 Times in 512 Posts
    Blog Entries
    5
    Ajax login pages may seem like a great idea but in practice they can be bad. Why? Well your attacker can submit multiple attempts until they get it right (and you're even saving them the bandwidth), it will be difficult to include random values to stop attackers, etc.

    Personally I think it's a great idea but so do hackers no doubt and thats why I would never implement an ajax powered login myself.
    See my new CodingForums Blog: http://www.codingforums.com/blogs/tangoforce/

    Many useful explanations and tips including: Cannot modify headers - already sent, The IE if (isset($_POST['submit'])) bug explained, unexpected T_CONSTANT_ENCAPSED_STRING, debugging tips and much more!

  • #3
    New Coder
    Join Date
    Oct 2010
    Posts
    99
    Thanks
    10
    Thanked 1 Time in 1 Post
    Quote Originally Posted by tangoforce View Post
    Ajax login pages may seem like a great idea but in practice they can be bad. Why? Well your attacker can submit multiple attempts until they get it right (and you're even saving them the bandwidth), it will be difficult to include random values to stop attackers, etc.

    Personally I think it's a great idea but so do hackers no doubt and thats why I would never implement an ajax powered login myself.
    Interesting take on it.. Thanks for that. Perhaps your right.
    I would however like to get this working for other areas of my application, such as adding records to DB, rather than sending to a new page if the current page could just say: Record saved...


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •