nielcleo Posted December 13, 2011 Share Posted December 13, 2011 Hi, i have here basic login system.. i tried to use ajax ..my problem is the data from the form was not send to checklogin.php thats why its always prompt WRONG USER NAME AND PASSWORD.. here's the code... login.php <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>New Page 1</title><script type="text/javascript" language="javascript" src="ceres.js"></script></head><body><table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"><tr><form name="login" method="post" action="checklogin.php"><td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"><tr><td colspan="3"><strong>Member Login </strong></td></tr><tr><td width="78">Username</td><td width="6">:</td><td width="294"><input name="myusername" type="text" id="myusername" onKeyPress="return force(this.name,this.form.id,event)"></td></tr><tr><td>Password</td><td>:</td><td><input name="mypassword" type="text" id="mypassword" ></td></tr><tr><td> </td><td> </td><td><input type="submit" name="Submit" value="Login" onclick="ajax_loadContent('main','checklogin.php');return false"></td></tr></table></td></form></tr></table> <div id="main_div"></div></body></html> index.php <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>New Page 1</title><script type="text/javascript" src="js/ajax.js"></script><script type="text/javascript" src="js/ajax-dynamic-content.js"></script></head><body> <div id="load_div"></div> <div id="main"></div> <script type="text/javascript">ajax_loadContent('main','login.php');</script></body></html> checklogin.php <?php$host="localhost"; // Host name$username=""; // Mysql username$password=""; // Mysql password$db_name=""; // Database name$tbl_name="login"; // Table name// Connect to server and select databse.mysql_connect("$host", "$username", "$password")or die("cannot connect");mysql_select_db("$db_name")or die("cannot select DB");// username and password sent from form$myusername=$_POST['myusername'];$mypassword=$_POST['mypassword'];// To protect MySQL injection (more detail about MySQL injection)$myusername = stripslashes($myusername);$mypassword = stripslashes($mypassword);$myusername = mysql_real_escape_string($myusername);$mypassword = mysql_real_escape_string($mypassword);$sql="SELECT * FROM $tbl_name WHERE userid='$myusername' and user_pass='$mypassword'";$result=mysql_query($sql);// Mysql_num_row is counting table row$count=mysql_num_rows($result);// If result matched $myusername and $mypassword, table row must be 1 rowif($count==1){// Register $myusername, $mypassword and redirect to file "login_success.php"session_register("myusername");session_register("mypassword");header("location:login_success.php");}else {echo "Wrong Username or Password";}?> Link to comment Share on other sites More sharing options...
JamesB Posted December 13, 2011 Share Posted December 13, 2011 can you show your ajax_loadContent() function? Link to comment Share on other sites More sharing options...
nielcleo Posted December 13, 2011 Author Share Posted December 13, 2011 can you show your ajax_loadContent() function? here isajax.js/* Simple AJAX Code-Kit (SACK) v1.6.1 *//* ©2005 Gregory Wild-Smith *//* www.twilightuniverse.com *//* Software licenced under a modified X11 licence, see documentation or authors website for more details */function sack(file) {this.xmlhttp = null;this.resetData = function() { this.method = "POST"; this.queryStringSeparator = "?"; this.argumentSeparator = "&"; this.URLString = ""; this.encodeURIString = true; this.execute = false; this.element = null; this.elementObj = null; this.requestFile = file; this.vars = new Object(); this.responseStatus = new Array(2); };this.resetFunctions = function() { this.onLoading = function() { }; this.onLoaded = function() { }; this.onInteractive = function() { }; this.onCompletion = function() { }; this.onError = function() { }; this.onFail = function() { };};this.reset = function() { this.resetFunctions(); this.resetData();};this.createAJAX = function() { try { this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { this.xmlhttp = null; } } if (! this.xmlhttp) { if (typeof XMLHttpRequest != "undefined") { this.xmlhttp = new XMLHttpRequest(); } else { this.failed = true; } }};this.setVar = function(name, value){ this.vars[name] = Array(value, false);};this.encVar = function(name, value, returnvars) { if (true == returnvars) { return Array(encodeURIComponent(name), encodeURIComponent(value)); } else { this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true); }}this.processURLString = function(string, encode) { encoded = encodeURIComponent(this.argumentSeparator); regexp = new RegExp(this.argumentSeparator + "|" + encoded); varArray = string.split(regexp); for (i = 0; i < varArray.length; i++){ urlVars = varArray[i].split("="); if (true == encode){ this.encVar(urlVars[0], urlVars[1]); } else { this.setVar(urlVars[0], urlVars[1]); } }}this.createURLString = function(urlstring) { if (this.encodeURIString && this.URLString.length) { this.processURLString(this.URLString, true); } if (urlstring) { if (this.URLString.length) { this.URLString += this.argumentSeparator + urlstring; } else { this.URLString = urlstring; } } // prevents caching of URLString this.setVar("rndval", new Date().getTime()); urlstringtemp = new Array(); for (key in this.vars) { if (false == this.vars[key][1] && true == this.encodeURIString) { encoded = this.encVar(key, this.vars[key][0], true); delete this.vars[key]; this.vars[encoded[0]] = Array(encoded[1], true); key = encoded[0]; } urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0]; } if (urlstring){ this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator); } else { this.URLString += urlstringtemp.join(this.argumentSeparator); }}this.runResponse = function() { eval(this.response);}this.runAJAX = function(urlstring) { if (this.failed) { this.onFail(); } else { this.createURLString(urlstring); if (this.element) { this.elementObj = document.getElementById(this.element); } if (this.xmlhttp) { var self = this; if (this.method == "GET") { totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString; this.xmlhttp.open(this.method, totalurlstring, true); } else { this.xmlhttp.open(this.method, this.requestFile, true); try { this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") } catch (e) { } } this.xmlhttp.onreadystatechange = function() { switch (self.xmlhttp.readyState) { case 1: self.onLoading(); break; case 2: self.onLoaded(); break; case 3: self.onInteractive(); break; case 4: self.response = self.xmlhttp.responseText; self.responseXML = self.xmlhttp.responseXML; self.responseStatus[0] = self.xmlhttp.status; self.responseStatus[1] = self.xmlhttp.statusText; if (self.execute) { self.runResponse(); } if (self.elementObj) { elemNodeName = self.elementObj.nodeName; elemNodeName.toLowerCase(); if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") { self.elementObj.value = self.response; } else { self.elementObj.innerHTML = self.response; } } if (self.responseStatus[0] == "200") { self.onCompletion(); } else { self.onError(); } self.URLString = ""; /* These lines were added by Alf Magne Kalleland ref. info on the sack home page. It prevents memory leakage in IE */ delete self.xmlhttp['onreadystatechange']; self.xmlhttp=null; self.responseStatus=null; self.response=null; self.responseXML=null; break; } }; this.xmlhttp.send(this.URLString); } }};this.reset();this.createAJAX();} ajax-dynamic-content.js /************************************************************************************************************Ajax dynamic contentCopyright (C) 2006 DTHMLGoodies.com, Alf Magne KallelandThis library is free software; you can redistribute it and/ormodify it under the terms of the GNU Lesser General PublicLicense as published by the Free Software Foundation; eitherversion 2.1 of the License, or (at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNULesser General Public License for more details.You should have received a copy of the GNU Lesser General PublicLicense along with this library; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USADhtmlgoodies.com., hereby disclaims all copyright interest in this scriptwritten by Alf Magne Kalleland.Alf Magne Kalleland, 2006Owner of DHTMLgoodies.com************************************************************************************************************/var enableCache = true;var jsCache = new Array();var dynamicContent_ajaxObjects = new Array();function ajax_showContent(divId,ajaxIndex,url,callbackOnComplete){var targetObj = document.getElementById(divId);targetObj.innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;if(enableCache){ jsCache[url] = dynamicContent_ajaxObjects[ajaxIndex].response;}dynamicContent_ajaxObjects[ajaxIndex] = false;ajax_parseJs(targetObj);if(callbackOnComplete) { executeCallback(callbackOnComplete);}}function executeCallback(callbackString) {if(callbackString.indexOf('(')==-1) { callbackString = callbackString + '()';}try{ eval(callbackString);}catch(e){}}function ajax_loadContent(divId,url,callbackOnComplete){if(enableCache && jsCache[url]){ document.getElementById(divId).innerHTML = jsCache[url]; ajax_parseJs(document.getElementById(divId)) evaluateCss(document.getElementById(divId)) if(callbackOnComplete) { executeCallback(callbackOnComplete); } return;}var ajaxIndex = dynamicContent_ajaxObjects.length;document.getElementById(divId).innerHTML = 'Loading content - please wait';dynamicContent_ajaxObjects[ajaxIndex] = new sack();if(url.indexOf('?')>=0){ dynamicContent_ajaxObjects[ajaxIndex].method='GET'; var string = url.substring(url.indexOf('?')); url = url.replace(string,''); string = string.replace('?',''); var items = string.split(/&/g); for(var no=0;no<items.length;no++){ var tokens = items[no].split('='); if(tokens.length==2){ dynamicContent_ajaxObjects[ajaxIndex].setVar(tokens[0],tokens[1]); } } url = url.replace(string,'');}dynamicContent_ajaxObjects[ajaxIndex].requestFile = url; // Specifying which file to getdynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url,callbackOnComplete); }; // Specify function that will be executed after file has been founddynamicContent_ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function}function ajax_parseJs(obj){var scriptTags = obj.getElementsByTagName('SCRIPT');var string = '';var jsCode = '';for(var no=0;no<scriptTags.length;no++){ if(scriptTags[no].src){ var head = document.getElementsByTagName("head")[0]; var scriptObj = document.createElement("script"); scriptObj.setAttribute("type", "text/javascript"); scriptObj.setAttribute("src", scriptTags[no].src); }else{ if(navigator.userAgent.toLowerCase().indexOf('opera')>=0){ jsCode = jsCode + scriptTags[no].text + '\n'; } else jsCode = jsCode + scriptTags[no].innerHTML; } }if(jsCode)ajax_installScript(jsCode);}function ajax_installScript(script){ if (!script) return; if (window.execScript){ window.execScript(script) }else if(window.jQuery && jQuery.browser.safari){ // safari detection in jQuery window.setTimeout(script,0); }else{ window.setTimeout( script, 0 ); }}function evaluateCss(obj){var cssTags = obj.getElementsByTagName('STYLE');var head = document.getElementsByTagName('HEAD')[0];for(var no=0;no<cssTags.length;no++){ head.appendChild(cssTags[no]);}} Link to comment Share on other sites More sharing options...
birbal Posted December 13, 2011 Share Posted December 13, 2011 what is the echo of $count in index.php? you may like to check it first that condition is matching correctly or not. Link to comment Share on other sites More sharing options...
nielcleo Posted December 13, 2011 Author Share Posted December 13, 2011 what is the echo of $count in index.php? you may like to check it first that condition is matching correctly or not. the number of rows.its working when im not using the ajax.. but will go.. http://url.com/checklogin.php and if it satisfy the statement it will redirect on the success page..i want to happen is load the checklogin.php without leaving the index.php..thats why itry to put ajax dynamic content to do that.. but the problem i encounter i always got WRONG USER NAME AND PASSWORD though i input the right one.. Link to comment Share on other sites More sharing options...
thescientist Posted December 13, 2011 Share Posted December 13, 2011 honestly, and I understand that you may be new to this so you probably aren't confident yet enough to think you can write your own code, but I would scrap all that JS code. There's way too much that you don't need that will only make your understanding, and consequently your debugging, harder. Simply, this is what your JS only really needs to do.1) use an event hander to capture the forms's submit event. Since you are using ajax, you don't even really need a form, you could just use a button and then use an onclick handler on that. If you use the form, remember to have it return false like you are doing nowhttp://www.w3schools...rm_onsubmit.asp 2) Have it call a function that makes an AJAX request to your PHP script, which get's the values of the username and password using document.getElementById('element_id_goes_here').value (use value for input, innerHTML for any other type of element).http://www.w3schools...uest_create.asp 3) Before the request is sent out, define a function for onreadystatechange to handle the response and alert the user accordingly.http://www.w3schools...statechange.asp At the most we are talking about a handful of lines of code. This will most undoubtably be a lot more practical then using all that other stuff. In the beginning i would just try echoing success and then add the header/additional loading functionality after the fact, as I'm not sure how that interacts within the context of an AJAX request. But echoing success will verify proof of concept, and right now that's what's important. Also, session_register is deprecated.http://php.net/manua...on-register.php Link to comment Share on other sites More sharing options...
nielcleo Posted December 13, 2011 Author Share Posted December 13, 2011 im not getting it on the part of the http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp :( im confused how to insert the php code on the function Link to comment Share on other sites More sharing options...
thescientist Posted December 13, 2011 Share Posted December 13, 2011 this has nothing to do with php (for now). I am merely suggesting simpler implementations for the javascript you are currently using. (i.e. replacing it with simpler code as outlined in my post) Link to comment Share on other sites More sharing options...
nielcleo Posted December 13, 2011 Author Share Posted December 13, 2011 i dont have background on javascript sir thats why i got confused what argument should i do.. to gives me the output that i need :( Link to comment Share on other sites More sharing options...
justsomeguy Posted December 13, 2011 Share Posted December 13, 2011 Your code is not sending the username and password. The ajax_loadContent function does not submit form data, it gets a file and displays it somewhere. If you want to submit form data you need to use something else. Link to comment Share on other sites More sharing options...
nielcleo Posted December 13, 2011 Author Share Posted December 13, 2011 what should i need to use:( Link to comment Share on other sites More sharing options...
justsomeguy Posted December 13, 2011 Share Posted December 13, 2011 The basics are pretty easy and are covered in the Javascript tutorials. There's an example here about sending a post request with form data: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp You would use document.getElementById to get the username and password elements and the values the user typed: http://www.w3schools.com/jsref/met_doc_getelementbyid.asp Link to comment Share on other sites More sharing options...
nielcleo Posted December 14, 2011 Author Share Posted December 14, 2011 how can i insert the validation in database.. with this..index.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Login</title> <script type="text/javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { var user_name = document.getElementById('user_name').value var password = document.getElementById('password').value var data = user_name + "|" + password; if(XMLHttpRequestObject) { var obj = document.getElementById(divID); obj.innerHTML = "Loading from " + dataSource; XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send("data=" + data); } return false; } </script></head><body><h2>Login to this site!</h2><form action="login.html" name="logonForm"><table> <tr> <td> User name: </td> <td> <input id="user_name" name="user_name" type="text" /> </td> </tr> <tr> <td> Password: </td> <td> <input id="password" name="password" type="password" /> </td> </tr> <tr> <td> </td> <td> <br /><input id="logon" type="submit" value="Login" onclick="return getData('checklogin.php', 'loginResultDiv')" /> </td> </tr></table><div id="loginResultDiv"> </div></form></body></html> checklogin.php <?php $data = $_POST['data']; echo "You entered >$data<"; if($data == 'uuserr|password') { echo "<h1>Hello! Welcome to the site!</h1>" ; } else { echo "<h1>Invalid Login! Try Again</h1>"; }?> and i also trying putting $data = stripslashes($data); $data = mysql_real_escape_string($data); for protection but it doesnt work Link to comment Share on other sites More sharing options...
JamesB Posted December 14, 2011 Share Posted December 14, 2011 well the quick fix is: list($username, $password) = explode('|', $_POST['data']);$username = mysql_real_escape_string($username);$password = mysql_real_escape_string($password); but it would be much better do send the username and password as 2 separate "post values". so this js: var data = user_name + "|" + password; XMLHttpRequestObject.send("data=" + data); could be changed to: var data = 'username='+encodeURIComponent(user_name)+'&password='encodeURIComponent(password); XMLHttpRequestObject.send(data); and the php can be: $username = $_POST['username'];$password = $_POST['password']; $username = mysql_real_escape_string($username);$password = mysql_real_escape_string($password); Link to comment Share on other sites More sharing options...
nielcleo Posted December 14, 2011 Author Share Posted December 14, 2011 well the quick fix is: list($username, $password) = explode('|', $_POST['data']);$username = mysql_real_escape_string($username);$password = mysql_real_escape_string($password); but it would be much better do send the username and password as 2 separate "post values". so this js: var data = user_name + "|" + password; XMLHttpRequestObject.send("data=" + data); could be changed to: var data = 'username='+encodeURIComponent(user_name)+'&password='encodeURIComponent(password); XMLHttpRequestObject.send(data); and the php can be: $username = $_POST['username'];$password = $_POST['password']; $username = mysql_real_escape_string($username);$password = mysql_real_escape_string($password); but the username and password doesnt send to the PHP.. Link to comment Share on other sites More sharing options...
justsomeguy Posted December 14, 2011 Share Posted December 14, 2011 How do you know? If you're not already, you should be using a debugger. There are links in my signature for the major browsers. You can use the debugger to look at the actual ajax request going out and look at the data that goes out with it, and also the response from PHP. In PHP, you can look at all of the post data using print_r: print_r($_POST); Link to comment Share on other sites More sharing options...
nielcleo Posted December 20, 2011 Author Share Posted December 20, 2011 here's my new code:index.php <html><head><script type="text/javascript">function loadXMLDoc(){var xmlhttp;var x=document.getElementById("username").valuevar y=document.getElementById("password").valueif (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","validate_logon.php?userid="+x+"&&userpass="+y,true);xmlhttp.send();}</script></head><body><input id="username" name="username" type="text" /><br><input id="password" name="password" type="text" /><div id="myDiv"><h2>Let AJAX change this text</h2></div><button type="button" onclick="loadXMLDoc()">Change Content</button></body></html> and i use $_GET['userid'] and $_GET['userpass'] and i echo it in validate_logon.php and its working displaying the userid and userpass that the user input on the forms.. but i encounter a problem on validate_logon.php when i use to connect it with my database.. i always got wrong password.. though i input correct login details..here's the validate_logon.php <?php$host="localhost"; // Host name$username=""; // Mysql username$password=""; // Mysql password$db_name=""; // Database name$tbl_name=""; // Table name// Connect to server and select databse.mysql_connect("$host", "$username", "$password")or die("cannot connect");mysql_select_db("$db_name")or die("cannot select DB");// username and password sent from form$myusername=$_GET['userid'];$mypassword=$_GET['userpass'];// To protect MySQL injection (more detail about MySQL injection)$myusername = stripslashes($myusername);$mypassword = stripslashes($mypassword);$myusername = mysql_real_escape_string($myusername);$mypassword = mysql_real_escape_string($mypassword);$sql="SELECT * FROM $tbl_name WHERE userid='$myusername' and user_pass='$mypassword' ";$result=mysql_query($sql);// Mysql_num_row is counting table row$count=mysql_num_rows($result);// If result matched $myusername and $mypassword, table row must be 1 rowif($count==1){// Register $myusername, $mypassword and redirect to file "login_success.php"session_register("myusername");session_register("mypassword");header("location:login_success.php");}else {echo "Wrong Username or Password";}echo "<br />";echo "<br />";echo "<br />";echo $myusername;echo "<br />";echo $mypassword;?> Link to comment Share on other sites More sharing options...
justsomeguy Posted December 20, 2011 Share Posted December 20, 2011 Instead of having both the username and password in the query, look up the user based on the username only and get the password from the database. If no records are returned then the username doesn't exist. If a record was returned, then compare the password in the database record with the password they entered. If they don't match you can always print both of them out to verify. Link to comment Share on other sites More sharing options...
JamesB Posted December 20, 2011 Share Posted December 20, 2011 you could also try changing && to & in this: xmlhttp.open("GET","validate_logon.php?userid="+x+"&&userpass="+y,true); Link to comment Share on other sites More sharing options...
nielcleo Posted December 21, 2011 Author Share Posted December 21, 2011 its not working its still not validate the input user and pass :(..but when i echoed only $_GET['userid'] and $_GET['userpass']; it displaying the data input from the form but when i used the code to validate it from the database its not working Link to comment Share on other sites More sharing options...
JamesB Posted December 21, 2011 Share Posted December 21, 2011 firstly check if an error occurred with the query: $result=mysql_query($sql);if (!$result) exit('error!'); if theres no error, make sure there's only 1 row in the table with the username and password you are trying, seeing as you are checking "== 1". Link to comment Share on other sites More sharing options...
justsomeguy Posted December 21, 2011 Share Posted December 21, 2011 You need to figure out why it's not working. If the database says it doesn't match, then it doesn't match. That's why I suggested checking for the username first, then you can print a message if the username is wrong, then check the password that the database returned and see if that matches. If it doesn't match then you can print both the password that the user entered and the password from the database to see why they don't match. You need to verify the data, you can't just guess what the problem might be. If it tells you it doesn't match, then figure out why. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.