?
Solved

Javascript not validating correctly with a boolean result

Posted on 2012-08-25
13
Medium Priority
?
562 Views
Last Modified: 2012-08-26
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

0
Comment
Question by:Easyrider43
  • 8
  • 5
13 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38333586
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
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333617
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
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333618
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
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38333647
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
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333651
so grabing it with javascript is poor programming? hmmm ill need to find another way of doing it
0
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333662
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
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38333667
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
 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 1000 total points
ID: 38333672
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
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333679
I did not know that, hmmmmm that could be my issue.. let me try that out
0
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333716
no still not working
0
 
LVL 1

Author Comment

by:Easyrider43
ID: 38333729
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
 
LVL 1

Author Closing Comment

by:Easyrider43
ID: 38333869
I figured it out, it was passing some header information I had in my framework. it works now ..........
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38334423
Thanks for the points, glad you got it working.
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month17 days, 9 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question