8 Replies - 3094 Views - Last Post: 08 March 2013 - 05:03 AM

#1 bteeple  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 01-May 11

Javascript/Ajax Login Script

Posted 05 March 2013 - 10:30 PM

Alright, I have been working with my website. And I have come to the conclusion to use Javascript/Ajax to handle my login so my php files are not just sitting out there. I created a simple website for testing my login form.

This file is called main.php.
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />

		<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
		Remove this if you use the .htaccess -->
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

		<title>main</title>
		<meta name="description" content="" />
		<meta name="author" content="Blake Teeple" />

		<meta name="viewport" content="width=device-width; initial-scale=1.0" />


	</head>

	<body>
		<div id="loginform">
		        <form  method="post">
            <table class="block-list">
                <tbody>
                    <tr>
                        <th><div>Username:</div></th>
                        <td><input type="text" class="text" id="username" name="username" /></td>
                    </tr>
                    <tr>
                        <th><div>Password:</div></th>
                        <td><input type="password" class="text" id="password" name="password" /></td>
                    </tr>
                    <tr>
                        <td> </td>
                        <td style="text-align: right; padding-top: 10px;"><input type="submit" value="Login" onclick="Core.login()"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
		</div>
			<script type="text/javascript" src="core.js"></script>
	</body>
</html>



As you can see it is very basic, but it gets the job done.

Here is my Javascript file including my Ajax server request.

This file is called core.js.

Core.login = function() {

	var username = document.getElementbyID('username'); /*Pulls the username and password to make sure something was entered*/
	var password = document.getElementbyID('password');
	if(username.value != null || password.value != null){
		Core.ajaxserver("login.php", "username: " + username.value + ",password: " + password.value);
		
	}
	else{
		alert("Error Password or Username")/*displays error message*/
	}
}
Core.ajaxserver = function(url, data) { /*Uses ajax to connect to a server to process data. */
	var xmlhttp;
		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest(); /*Firefox and other modern browsers. */
		} else { 
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); /*Internet Explorer*/
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				data = xmlhttp.responseText.split("|");					
					for (i = 0; i < data.length; i++){ /*Loop to parse the variables for the server. */
						var one = Core.decodeURI(data[parseInt(i)]);
						var two = Core.decodeURI(data[parseInt(i) + 1]);
						var three = Core.decodeURI(data[parseInt(i) + 2]);
						var four = Core.decodeURI(data[parseInt(i) + 3]);
						var five = Core.decodeURI(data[parseInt(i) + 4]);
						
							if (window.Core[one]) {
								window.Core[one](two,three,four,five);
							}
					}		
			} else {
				return false;
			}
		}
		if (!data) {
			data = "";
		}
		data = data.replace(/: /gi, "=");
		data = data.replace(/:/gi, "=");
		data = data.replace(/, /gi, "&");
		data = data.replace(/,/gi, "&");

		data = data + "&current_sessionid=" + current_sessionid;
		
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send(data);
}
Core.decodeURI = function (text) {
	return decodeURIComponent(text);
}


After troubleshooting and using Alerts to pin point if it was my Javascript or Ajax, I have come to the conclusion I believe it is my Ajax. In my Core.Login() script I put alerts to see if the script was getting the right values, to which it was. My main problem is that I am lost at what is going wrong with my Ajax server request. Any help or advice would be grateful. Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Javascript/Ajax Login Script

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,227
  • Joined: 08-June 10

Re: Javascript/Ajax Login Script

Posted 05 March 2013 - 11:17 PM

View Postbteeple, on 06 March 2013 - 06:30 AM, said:

My main problem is that I am lost at what is going wrong with my Ajax server request. Any help or advice would be grateful.

since we donít know your server script, we canít say whether there is something wrong.

but the most crucial point for a session is its session ID. why do you try to pass a session ID on login? usually the session ID in the cookie (unless disabled) is passed automatically. when your login request returns, do you set the session ID/cookie anywhere?
Was This Post Helpful? 0
  • +
  • -

#3 bteeple  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 01-May 11

Re: Javascript/Ajax Login Script

Posted 06 March 2013 - 12:47 AM

<?php
    $uname = "";
    $pword = "";
    $errorMessage = "";

    function quote_smart($handle, $value)
    {
        if (get_magic_quotes_gpc())
        {
            $value = stripslashes($value);
        }

        if (!is_numeric($value))
        {
            $value = "'" . mysqli_real_escape_string($handle, $value) . "'";
        }
        return $value;
    }

    if (isset($_REQUEST['submit']))
    {
        $uname = $_POST['username'];
        $pword = $_POST['password'];

        $uname = htmlspecialchars($uname);
        $pword = htmlspecialchars($pword);

        $con = mysqli_connect("127.0.0.1", "root", "","users");

        if ($con)
        {
            $uname = quote_smart($con, $uname);
            $pword = quote_smart($con, $pword);

            $SQL = "SELECT * FROM users WHERE username = ".$uname." AND password = ".$pword."";

            $result = mysqli_query($con, $SQL);
            $num_rows = mysqli_fetch_array($result,MYSQLI_NUM);


                if ($num_rows > 0)
                {
                    session_start();
                    $_SESSION['login'] = "1";
                    header ("Location: home.php");
                    exit;
                }
                else
                {
                    session_start();
                    $_SESSION['login'] = "";
                    header ("Location: regpage.php");
                    exit;
                }   
            }
            else
            {
                $errorMessage = "Error logging on";
            }
            mysqli_close($con);
    }
?>



That is my server script to login. I have that session ID there because I use the Core.ajaxserver() method to access my databases for other things while the user is logged in. Should I create a separate ajax function for just logging in?
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,227
  • Joined: 08-June 10

Re: Javascript/Ajax Login Script

Posted 06 March 2013 - 01:58 AM

ok, there is a lot to improve.
- if you only want to know, whether there is a match in the DB, query for the number of matches, i.e. COUNT(). any data you fetch and donít use are superfluous.

- if you use Prepared Statements, you donít need to escape your values.

- donít test for a submit button, always test for the data you need (which is why it doesnít work)
Was This Post Helpful? 0
  • +
  • -

#5 bteeple  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 01-May 11

Re: Javascript/Ajax Login Script

Posted 06 March 2013 - 12:15 PM

Alright, so I took my chances with prepared statements. Here is my new login.php.


<?php
$uname = $_POST['username'];
$pword = $_POST['password'];

$con = mysqli_connect("127.0.0.1", "root", "", "users");

if(!$con){
	echo "Connection failure " . mysqli_connect_errno();
	exit();
}

if($stmt = $con -> prepare("SELECT * FROM users WHERE username = ".$uname." AND password = ".$pword."")){
	$stmt -> bind_param("ss", $uname, $pword);
	$stmt -> execute($stmt);
	$stmt -> bind_result($result);
	$stmt -> fetch($stmt);
	
	
    $num_rows = mysqli_fetch_array($stmt,MYSQLI_NUM);


   if ($num_rows > 0)
      {
        	session_start();
     		$_SESSION['login'] = "1";
     		header ("Location: home.php");
      		exit;
     }
     else
     {
            session_start();
            $_SESSION['login'] = "";
            header ("Location: regpage.php");
            exit;
     }
	
	
	$stmt -> close();
}


$con -> close();

?>


I know I haven't implemented the COUNT() functionality yet, I just wanted to make sure I got the prepared statements down, and they were done right. Is this how it should be done?


Also I did some research on the COUNT() function. And I started something along the lines of this:

if($stmt = $con -> prepare("SELECT COUNT(*) FROM users WHERE username = ".$uname." AND password = ".$pword."")){
	$stmt -> bind_param("ss", $uname, $pword);
	$stmt -> execute($stmt);
	$stmt -> bind_result($result);
	$stmt -> fetch($stmt);
	$stmt -> close();
}



I guess my main issue is that I don't know how to properly use the COUNT() function. I tried searching the php manual and I couldn't find anything that gave me a definitive answer on how to use it. And most tutorials on the google search were using mysql and not prepared statements.
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3467
  • View blog
  • Posts: 11,768
  • Joined: 12-December 12

Re: Javascript/Ajax Login Script

Posted 06 March 2013 - 12:31 PM

You are not using prepared statements correctly. I don't know what documentation you are studying but you should read the docs.
Was This Post Helpful? 0
  • +
  • -

#7 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,227
  • Joined: 08-June 10

Re: Javascript/Ajax Login Script

Posted 06 March 2013 - 12:34 PM

View Postbteeple, on 06 March 2013 - 08:15 PM, said:

I just wanted to make sure I got the prepared statements down, and they were done right. Is this how it should be done?

no, not at all. the issue with prepared statements is to separate SQL statement and SQL data. hence the use of placeholders (? for MySQLi and ? or :placeholder in PDO).


View Postbteeple, on 06 March 2013 - 08:15 PM, said:

I guess my main issue is that I don't know how to properly use the COUNT() function. I tried searching the php manual and I couldn't find anything that gave me a definitive answer on how to use it. And most tutorials on the google search were using mysql and not prepared statements.

you wonít find COUNT() in the PHP Manual, because youíll find it in the [My]SQL Manual (e.g. here).

besides that, the difference between COUNT() in a mysql_* query and in a Prepared Statement is Ö zero, since the statement part is the same for both.
Was This Post Helpful? 1
  • +
  • -

#8 bteeple  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 01-May 11

Re: Javascript/Ajax Login Script

Posted 07 March 2013 - 10:10 PM

Alright, I played around with my login script and I think I have it the way I like. Although, I am still having a few bugs. For some reason it is not logging me in even though I am typing the exact username and password that is in my database. Any ideas?

It keeps skipping to my "Wrong username or password" statement. As it's not seeing the rows.

<?php
session_start();
$mysqli = new mysqli("127.0.0.1", "root", "", "users");
if(isset($_POST['username']) && isset($_POST['password'])){
        $stmt = $mysqli->prepare("SELECT Username, Password FROM users WHERE Username=? AND  Password=? LIMIT 1");
        $email = $_POST['username'];
        $password = $_POST['password'];
        $stmt->bind_param('ss', $user, $pword);
        $stmt->execute();
        $stmt->bind_result($user, $pword);
        $stmt->store_result();
        if($stmt->num_rows == 1) 
            {
                while($stmt->fetch())

                  {$_SESSION['Logged'] = 1;
                   $_SESSION['Username'] = $user;
                   header('Location: home.php');
                   exit();
                   }

            }
            else {
                echo "Wrong Username or Password!";
				
            }
			$stmt->free_result();
            $stmt->close();
            
        }
        else 
        {   
		echo "You don't have an account, you may register now!";
        }
$mysqli->close();
?>

Was This Post Helpful? 0
  • +
  • -

#9 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,227
  • Joined: 08-June 10

Re: Javascript/Ajax Login Script

Posted 08 March 2013 - 05:03 AM

it’s not seeing rows because the query does not return any. the $user and $pword variables are always NULL.

besides that, your logic is error prone. why are you requesting the username and password from the DB using username and password? what you want to know is whether there is a match or not (resp. how many matches there are). which is a classical use case for COUNT(). this way you’ll always have a single row (if you don’t, then your query *failed*) from which you only need to read the value.

i.e. SELECT COUNT(*) FROM users WHERE Username=? AND Password=?

This post has been edited by Dormilich: 08 March 2013 - 05:03 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1