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 8 of 8
  1. #1
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Ajax code isn't working

    Code:
    function addEvent(elem,type,func) {
    	var obj = document.getElementById(elem);
    	if(window.addEventListener) {
    		obj.addEventListener(type,func,false);
    	}
    	if(window.attachEvent) {
    		obj.attachEvent('on'+type,func);
    	}
    }
    
    function $e(obj) {
    	if(obj) obj = document.getElementById(obj);
    	if(!obj) return;
    	return obj;
    }	
    
    function homeFunc() {
    	$e('home-wrapper').innerHTML = "<div id=\"choose-container\"><span class=\"choose-buttons\" onclick=\"loginFunc()\">Login Exisiting Account</span><span class=\"choose-buttons\" id=\"createAcct\">Create An New Account</span><span class=\"choose-buttons-highscores\" id=\"createAcct\">Highscores Table</span>";
    }
    
    function loginFunc() {
    	$e('home-wrapper').innerHTML = "<div id=\"login-container\"><div id=\"error-field\"></div><form method=\"post\" onsubmit=\"return validate_login()\" action=\"./index.php\"><label for=\"username\">Username</label><input name=\"username\" id=\"username\" class=\"input\" type=\"text\" />  <label for=\"password\">Password</label><input name=\"password\" id=\"password\" class=\"input\" type=\"password\" /><input name=\"login\" type=\"submit\" value=\"Login\" class=\"loginButtonClass\" /><div id=\"loginQuickLinks\"><span class=\"loginQuickLinks\" onclick=\"homeFunc()\">Register</span>&nbsp;-&nbsp;<span class=\"loginQuickLinks\">Forgot password?</span></form></div></div>";
    }
    
    function createAcct() {
    	alert("Create An Account");
    }
    
    function validate_usr() {
    	var usr = $e('username');
    	var pwd = $e('password');
    	
    	if(usr.value.length <= 0 && pwd.value.length <= 0) {
    		 loginErrorMsg('Please supply a username and password.');
    		return false;
    	}
    	if(usr.value.length >= 1 && pwd.value.length <= 0) {
    		loginErrorMsg('Please supply a password.');
    		return false;
    	}
    	if(pwd.value.length >= 5 && usr.value.length <= 0) {
    		loginErrorMsg('Please supply a username.');
    		return false;
    	}
    	if(pwd.value.length < 5) {
    		loginErrorMsg('Invalid username or password.');
    		return false;
    	}
    	
    	if(usr.value.length >= 1 && pwd.value.length >= 5) {
    	$e('error-field').style.cssText='display:block;';
    	$e('error-field').innerHTML = "<img src=\"/images/ajax-loader.gif\" /> <span style=\"color:#ffffff\">Loading...</span>";
    		var req;
    		var params = 'user='+encodeURIComponent(usr.value.toLowerCase())+'&pass='+encodeURIComponent(pwd.value.toLowerCase());
    		if(window.XMLHttpRequest) {
    			req = new XMLHttpRequest();
    		}
    		if(window.ActiveXObject) {
    			req = new ActiveXObject("Msxml2.XMLHTTP" || "Microsoft.XMLHTTP");
    		}
    
    		req.open('POST','server/userChck.php',true);
    		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		req.send(params);
    		
    		req.onreadystatechange = req;
    		if(req.readyState == 4 && req.status == 200) {
    			if(req.responseText == 0) {
    				window.scrollTo(0,1);
    				setTimeout(function(){loginErrorMsg('Invalid username or password');},1000);
    				return false;
    			}
    			
    		}
    		
    	}
    	
    	return true;
    }
    
    function loginErrorMsg(msg) {
    		window.scrollTo(0,1);
    	$e('error-field').innerHTML = msg;
    	$e('error-field').style.cssText='display:block';
    }
    
    function validate_login() {
    
    	var isTurn = (!validate_usr()) ? false : true;
    	
    	return isTurn;
    	
    }
    
    window.onload = function() {
    	setTimeout(function(){window.scrollTo(0,1);},100);
    	addEvent('loginButton','click',loginFunc);
    	addEvent('createAcct','click',homeFunc);
    }
    This code works fine when I set this line to false

    Code:
    req.open('POST','server/userChck.php',false);
    but as soon as I set this to true. I doesn't work.... What am I doing wrong here?

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    You can't just return true/false from an AJAX request that uses async (the true that you noted).

    YOu have to reorganize your code to have the AJAX response *trigger* something on the page.

    Since you don't show how/where you invoke validate_login() [which in turn call validate_user()] we can't really guess. It will probably be easier for you to leave that as false if you don't understand this.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts
    validate_login() is invoked onsubmit on the form. The bigger problem that I am having is that when I submit the form, I have a ajax loader to inform the user that the ajax is doing its thing. The problem here is that the ajax loader isn't showing until after the request is complete... Which kind of defeats the purpose of having a "loading please wait" to the user if it doesn't trigger until after its finish. I figured this was caused because the request wasn't asynchronous. So in hopes of fixing this just by changing the parameter to true was without a doubt wrong for me to do so. I know I am just rambling now but does anyone know how I can go about fixing this?

    This is the whole form that I am using in this bit of code here:
    Code:
    function loginFunc() {
    	$e('home-wrapper').innerHTML = "<div id=\"login-container\"><div id=\"error-field\"></div><form method=\"post\" onsubmit=\"return validate_login()\" action=\"./index.php\"><label for=\"username\">Username</label><input name=\"username\" id=\"username\" class=\"input\" type=\"text\" />  <label for=\"password\">Password</label><input name=\"password\" id=\"password\" class=\"input\" type=\"password\" /><input name=\"login\" type=\"submit\" value=\"Login\" class=\"loginButtonClass\" /><div id=\"loginQuickLinks\"><span class=\"loginQuickLinks\" onclick=\"homeFunc()\">Register</span>&nbsp;-&nbsp;<span class=\"loginQuickLinks\">Forgot password?</span></form></div></div>";
    }
    Last edited by Jon W; 12-06-2010 at 08:24 AM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    > I figured this was caused because the request wasn't asynchronous.

    Correct.

    To fix this you *MUST NOT* allow the form to submit, EVER.

    Instead, you would have your AJAX code call the document.forms[0].submit() when and if the login is verified.

    In other words, you would do
    Code:
    <form ... onsubmit="validate_login(); return false;">
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts
    Okay, I've changed a few bits of my code to the way you said I should have it set up. The onsubmit is now set to return false always, and I set in my code if the user name comes back valid then submit the form. This code still isn't working. I did some alert test to see where the code stops, and it stops at

    Code:
    req.open('POST','server/userChck.php',true);
    and it doesn't seem to want to go beyond that point. What else could I possibly be doing wrong here?


    Entire Code:
    Code:
    function addEvent(elem,type,func) {
    	var obj = document.getElementById(elem);
    	if(window.addEventListener) {
    		obj.addEventListener(type,func,false);
    	}
    	if(window.attachEvent) {
    		obj.attachEvent('on'+type,func);
    	}
    }
    
    function $e(obj) {
    	if(obj) obj = document.getElementById(obj);
    	if(!obj) return;
    	return obj;
    }	
    
    function homeFunc() {
    	$e('home-wrapper').innerHTML = "<div id=\"choose-container\"><span class=\"choose-buttons\" onclick=\"loginFunc()\">Login Exisiting Account</span><span class=\"choose-buttons\" id=\"createAcct\">Create An New Account</span><span class=\"choose-buttons-highscores\" id=\"createAcct\">Highscores Table</span>";
    }
    
    function loginFunc() {
    	$e('home-wrapper').innerHTML = "<div id=\"login-container\"><div id=\"error-field\"></div><form method=\"post\" onsubmit=\"validate_login(); return false;\" action=\"./index.php\"><label for=\"username\">Username</label><input name=\"username\" id=\"username\" class=\"input\" type=\"text\" />  <label for=\"password\">Password</label><input name=\"password\" id=\"password\" class=\"input\" type=\"password\" /><input name=\"login\" type=\"submit\" value=\"Login\" class=\"loginButtonClass\" /><div id=\"loginQuickLinks\"><span class=\"loginQuickLinks\" onclick=\"homeFunc()\">Register</span>&nbsp;-&nbsp;<span class=\"loginQuickLinks\">Forgot password?</span></form></div></div>";
    }
    
    function createAcct() {
    	alert("Create An Account");
    }
    
    function validate_usr() {
    	var usr = $e('username');
    	var pwd = $e('password');
    	
    	if(usr.value.length <= 0 && pwd.value.length <= 0) {
    		 loginErrorMsg('Please supply a username and password.');
    		return false;
    	}
    	if(usr.value.length >= 1 && pwd.value.length <= 0) {
    		loginErrorMsg('Please supply a password.');
    		return false;
    	}
    	if(pwd.value.length >= 5 && usr.value.length <= 0) {
    		loginErrorMsg('Please supply a username.');
    		return false;
    	}
    	if(pwd.value.length < 5) {
    		loginErrorMsg('Invalid username or password.');
    		return false;
    	}
    	
    	if(usr.value.length >= 1 && pwd.value.length >= 5) {
    	$e('error-field').style.cssText='display:block;';
    	$e('error-field').innerHTML = "<img src=\"/images/ajax-loader.gif\" /> <span style=\"color:#ffffff\">Loading...</span>";
    		var req;
    		var params = 'user='+encodeURIComponent(usr.value.toLowerCase())+'&pass='+encodeURIComponent(pwd.value.toLowerCase());
    		if(window.XMLHttpRequest) {
    			req = new XMLHttpRequest();
    		}
    		if(window.ActiveXObject) {
    			req = new ActiveXObject("Msxml2.XMLHTTP" || "Microsoft.XMLHTTP");
    		}
    		
    		req.open('POST','server/userChck.php',true);
    		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		req.send(params);
    		
    		req.onreadystatechange = req;
    		if(req.readyState == 4) {
    			if(req.responseText == 0) {
    				window.scrollTo(0,1);
    				setTimeout(function(){loginErrorMsg('Invalid username or password');},1000);
    				return false;
    			}
    			else {
    				alert(req.responseText);
    				document.forms[0].submit();
    			}
    			
    		}
    		
    	}
    	
    	return true;
    }
    
    function loginErrorMsg(msg) {
    		window.scrollTo(0,1);
    	$e('error-field').innerHTML = msg;
    	$e('error-field').style.cssText='display:block';
    }
    
    function validate_login() {
    
    	var isTurn = (!validate_usr()) ? false : true;
    	
    	return isTurn;
    	
    }
    
    window.onload = function() {
    	setTimeout(function(){window.scrollTo(0,1);},100);
    	addEvent('loginButton','click',loginFunc);
    	addEvent('createAcct','click',homeFunc);
    }

  • #6
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Code:
    req.onreadystatechange = req;
    The above line makes no sense. You need to assign a function to the event handler, not the request object.

  • #7
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts
    I fixed this by setting onreadystatechange to equal a function. Though I don't really want to put all of:

    Code:
    		req.onreadystatechange = function() {
    		
    		if(req.readyState == 4 && req.status == 200) {
    			if(req.responseText == 0) {
    				window.scrollTo(0,1);
    				loginErrorMsg('Invalid username or password');
    				return false;
    			}
    			else {
    				document.forms[0].submit();
    			}
    			
    		}
    	}
    That inside a function. Why does this work when it is made into a function?

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Because it *NEEDS* to be a function.

    The "send" code is DONE and will return *immediately* after the send() call.

    That function is now "registered" as the event handler for the CALLBACK (event) that happens upon completion of the Request/Response round trip.

    If it's not a function, it can't be called.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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