Javascript not validating correctly with a boolean result

Experts I really need your help.... I've had trouble with this all day and im stressed. in the front page you enter your username and password and click submit, the javascript below grabs the information sends it to php script to validate and checks for a true value if not it displays an error, well it doesnt matter what username or password I type its always giving me the error. so I must be using the true or fase wrong somewhere i dont know. Please look over my code and see if you have any suggestions. Thanks Guys



This is the Javascript/Ajax portion where it send and receives the information from the php code

function login() {
	var password;
	var username;
	check_values = function() {
	 	var	user = document.getElementById('email').value;
	 	var	pass = document.getElementById('pass').value;
	 
	 		if (user == "" || pass == "") {
	 			document.getElementById('errors').innerHTML = "Either Username or Password is Blank";
	 		} else {
	 			document.getElementById('errors').innerHTML = "";
	 			process_login(user, pass);
	 			}	 			
	 	}
	process_login = function(username, password) {
	connect_ajax();
	xmlhttp.onreadystatechange=function()
			{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
					{
					var answer = xmlhttp.responseText;
					if (answer) {
						document.getElementById('errors').innerHTML = '';
						document.getElementById('errors').innerHTML = 'Logging In...';
						document.getElementById('ad_login').innerHTML = '';
						document.getElementById('ad_login').innerHTML = answer;
						window.location = 'members/home';
						}
					else 
						{
						document.getElementById('errors').innerHTML = '';
						document.getElementById("errors").innerHTML = 'Error In Login';
						document.getElementById('ad_login').innerHTML = '';
						document.getElementById('ad_login').innerHTML = answer + "you answered 0";
						}
					}
			}
			var params="id="+username+"&pass="+password;
			xmlhttp.open("POST","http://www.****.com/service/login", true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.send(params);
	 	}

Open in new window


This is the php Code that checks it in the database and returns a true or false to the javascript code above
if (isset($_POST['id']))
	{
		$username = $_POST['id'];
	}
if (isset($_POST['pass']))
	{
		$password = md5($_POST['pass']);
	}

if (isset($username) && isset($password))
	{
		$statement = "SELECT acct_num, email, password FROM members WHERE email = '$username' && password = '$password'";
		$explore = new explore('main');
		$acct_num = $explore->fetch($statement, 1);
		if ($acct_num)
			{
			if (isset($acct_num[0]['acct_num']))
				{
		    	session_cache_limiter ('nocache');
				session_start();
	        	$_SESSION['userid'] = $acct_num[0]['acct_num'];
           		return 1;
				} 
			
			} 
		
	} 
	

Open in new window


Here is the explore class if you wanted to look  at that also...

class explore{
    private $user;
    private $pass;
    private $host;
    private $db_name;
	private $connect;
    
    function __construct($db = null) {

        if ($db === null) { $this->db_name =  db_name; } else { $this->db_name = $db; }  
				$this->user = u;
				$this->pass = pass;
				$this->host = host;                                          
   }
    /** startup function used to connect to the database */
    public function startup()
    {
    	$capture = new error("Database Has Received An Error");
    	$diary   = new diary();
        $this->connect = mysql_connect($this->host, $this->user, $this->pass) or die ($diary->problem(mysql_error()));
        //$diary->problem($connect);
        if ($this->connect)                                                                              
                {
                mysql_select_db($this->db_name) or die ($diary->problem(mysql_error()) . '' . $capture->no_data());
                }
                else
                {
               $diary->problem('Mysql Could not connect to database');                                                     
                }
    }
    
	/** explore your database with the fetch statment and store it into the $bank[] array */
    public function fetch($statement, $boolean_value = null)
    {
		$diary = new diary();
        $this->startup();                                                          
        $result = mysql_query($statement) or die ($diary->problem('Problem in query while fetching [ ' . mysql_error() . ' ]'));  
        $bank = array();
        if (mysql_num_rows($result))
            {
	    	while ($row = mysql_fetch_assoc($result))
				{
					$bank[] = $row;
				}
			return $bank;
			} 
			$this->turnoff($result, $this->connect);	
			
    }
	
	public function give($statement)
	{
		$diary = new diary();
        $this->startup();                                                          
        mysql_query($statement) or die ($diary->problem('Problem in query while Inserting [ ' . mysql_error() . ' ]'));  
	}
	
    /** Test your statment with fetch_is_true() function returns true or false */
    public function fetch_is_true($statement)
    {
        $this->startup();                                                           
        $result = mysql_query($statement) or die ('<br>Error query: ' . mysql_error() . '<br>');  
        $num_result = mysql_num_rows($result);
		return $num_result;
    }
    
	
	/** Close explore and clear the buffer */
    public function turnoff($result, $connect)                                                      
    {
        mysql_free_result($result);
        mysql_close($this->connect);
    }
    
}  

Open in new window

LVL 1
Easyrider43Asked:
Who is Participating?
 
Dave BaldwinConnect With a Mentor Fixer of ProblemsCommented:
You do know that you have to 'echo' the response on the PHP page so the AJAX will receive it?  'return' just returns it to the place in the PHP page that called it.
0
 
Dave BaldwinFixer of ProblemsCommented:
In your PHP, you have to return something for both states.  If you don't return anything, then if (xmlhttp.readyState==4 && xmlhttp.status==200) is never true and nothing happens.  Change your PHP to return '1' for success and '0' for failure.  Then in your javascript, test for if(answer == '1') and if(answer == '0').  Do not try to return a number / binary 1, it won't make it thru because it's not a legal character.  Send text characters '1' and '0'.
0
 
Easyrider43Author Commented:
now it just return null, I got to be missing something, here is my updated Code

if (isset($_POST['id']))
	{
		$username = $_POST['id'];
	}
if (isset($_POST['pass']))
	{
		$password = md5($_POST['pass']);
	}

if (isset($username) && isset($password))
	{
		$statement = "SELECT acct_num, email, password FROM members WHERE email = '$username' && password = '$password'";
		$explore = new explore('main');
		$acct_num = $explore->fetch($statement);
		if ($acct_num)
			{
			if (isset($acct_num[0]['acct_num']))
				{
		    	session_cache_limiter ('nocache');
				session_start();
	        	$_SESSION['userid'] = $acct_num[0]['acct_num'];
           		return '1';
				} 
			else 
				{
					
				return '0';
				}
			
			} 
		
	} 

Open in new window



and the Javascript

function login() {
	var password;
	var username;
	check_values = function() {
	 	var	user = document.getElementById('email').value;
	 	var	pass = document.getElementById('pass').value;
	 
	 		if (user == "" || pass == "") {
	 			document.getElementById('errors').innerHTML = "Either Username or Password is Blank";
	 		} else {
	 			document.getElementById('errors').innerHTML = "";
	 			process_login(user, pass);
	 			}	 			
	 	}
	process_login = function(username, password) {
	connect_ajax();
	xmlhttp.onreadystatechange=function()
			{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
					{
					var answer = xmlhttp.responseText;
					if (answer == '1') {
						document.getElementById('errors').innerHTML = '';
						document.getElementById('errors').innerHTML = 'Logging In...';
						document.getElementById('ad_login').innerHTML = '';
						document.getElementById('ad_login').innerHTML = answer;
						window.location = 'members/home';
						}
					if (answer == '0')
						{
						document.getElementById('errors').innerHTML = '';
						document.getElementById("errors").innerHTML = 'Error In Login';
						document.getElementById('ad_login').innerHTML = '';
						document.getElementById('ad_login').innerHTML = answer + "you answered 0";
						}
					}
			}
			var params="id="+username+"&pass="+password;
			xmlhttp.open("POST","http://*************/service/login", true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.send(params);
	 	}

Open in new window


and the explore class

class explore{
    private $user;
    private $pass;
    private $host;
    private $db_name;
	private $connect;
    
    function __construct($db = null) {

        if ($db === null) { $this->db_name =  db_name; } else { $this->db_name = $db; }  
				$this->user = u;
				$this->pass = pass;
				$this->host = host;                                          
   }
    /** startup function used to connect to the database */
    public function startup()
    {
    	$capture = new error("Database Has Received An Error");
    	$diary   = new diary();
        $this->connect = mysql_connect($this->host, $this->user, $this->pass) or die ($diary->problem(mysql_error()));
        //$diary->problem($connect);
        if ($this->connect)                                                                              
                {
                mysql_select_db($this->db_name) or die ($diary->problem(mysql_error()) . '' . $capture->no_data());
                }
                else
                {
               $diary->problem('Mysql Could not connect to database');                                                     
                }
    }
    
	/** explore your database with the fetch statment and store it into the $bank[] array */
    public function fetch($statement)
    {
		$diary = new diary();
        $this->startup();                                                          
        $result = mysql_query($statement) or die ($diary->problem('Problem in query while fetching [ ' . mysql_error() . ' ]'));  
        $bank = array();
        if (mysql_num_rows($result))
            {
	    	while ($row = mysql_fetch_assoc($result))
				{
					$bank[] = $row;
				}
			return $bank;
			} 
		else 
			{
				return 0;
			}
			$this->turnoff($result, $this->connect);	
			
    }
	
	public function give($statement)
	{
		$diary = new diary();
        $this->startup();                                                          
        mysql_query($statement) or die ($diary->problem('Problem in query while Inserting [ ' . mysql_error() . ' ]'));  
	}
	
    /** Test your statment with fetch_is_true() function returns true or false */
    public function fetch_is_true($statement)
    {
        $this->startup();                                                           
        $result = mysql_query($statement) or die ('<br>Error query: ' . mysql_error() . '<br>');  
        $num_result = mysql_num_rows($result);
		return $num_result;
    }
    
	
	/** Close explore and clear the buffer */
    public function turnoff($result, $connect)                                                      
    {
        mysql_free_result($result);
        mysql_close($this->connect);
    }
    
}  

Open in new window

0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Easyrider43Author Commented:
I should also mention that it does validate the username and password and it opens a session also, so it works im just having trouble having the php tell the javascript that it returns true.
0
 
Dave BaldwinFixer of ProblemsCommented:
You're getting null because you have an error in your PHP. If this $acct_num[0]['acct_num']) is the row you get back from your query, you can have either a number or a name for the array index but not both.  You might want to make up a simple form page (without AJAX) that posts to your PHP page so you can see what it actually returns.

In addition, username and password should be urlencoded with encodeURI(uri) http://www.w3schools.com/jsref/jsref_encodeuri.asp before it is sent.  Especially if you are allowing any special characters in them.
0
 
Easyrider43Author Commented:
so grabing it with javascript is poor programming? hmmm ill need to find another way of doing it
0
 
Easyrider43Author Commented:
the $acct_num[0]['acct_num'] is getting assigned to the session userid variable then im returning a 1 to say the query was true meaning complete
0
 
Dave BaldwinFixer of ProblemsCommented:
No, AJAX is fine except that it can be difficult to troubleshoot because the errors don't show up.  I would use a regular form page to test it until it worked properly and then I would go back to the AJAX version.

If $acct_num[0]['acct_num'] is working then ok.  Your logic isn't clear to me.
0
 
Easyrider43Author Commented:
I did not know that, hmmmmm that could be my issue.. let me try that out
0
 
Easyrider43Author Commented:
no still not working
0
 
Easyrider43Author Commented:
all right when I alert the response with the correct username it the alert says 1 like it should-- and when the username is wrong it alerts 0 like it should, BUT!! the if statement cant read the 1 or 0 in the answer variable. Why??
0
 
Easyrider43Author Commented:
I figured it out, it was passing some header information I had in my framework. it works now ..........
0
 
Dave BaldwinFixer of ProblemsCommented:
Thanks for the points, glad you got it working.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.