Form validation using javascript in php application

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
nbt725
Forum Newbie
Posts: 11
Joined: Thu Aug 16, 2007 6:08 am

Form validation using javascript in php application

Post by nbt725 »

Dear Sir,

Hello ! I need to validate my login form which is displayed using <div> to give sliding effect and not to refresh page, hence can't use generic php submit but to validate using javascript and/or ajax. And in log in form I need to validata user id and password to my mysql database.

Please guide me.

Thanks & Regards,

Naimesh Trivedi
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

What are you having trouble with?
nbt725
Forum Newbie
Posts: 11
Joined: Thu Aug 16, 2007 6:08 am

Post by nbt725 »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


[quote="feyd"]What are you having trouble with?[/quote]

Code: Select all

<script type="text/javascript" src="ajax.js"></script>
<script type="text/Javascript">
var ret_flag;
var ajax = new sack();
function val_login()
{
	
	var user_name = document.getElementById('user_name').value;
	
	var password  = document.getElementById('password').value;
	if(user_name != "")
	{
		ajax.requestFile = 'login_valid.php?user_name='+user_name;	// Specifying which file to get
		ajax.onCompletion = login_action;	// Specify function that will be executed after file has been found
		ajax.runAJAX();		// Execute AJAX function
	}

if (ret_flag == "Valid")
{
	return true;	
}
else
{
	alert ("Invalid User Id or Password !!!");
	return false;
}
}

function login_action()
{
	var obj = document.getElementById('ret_mode');
	eval(ajax.response);	// Executing the response from Ajax as Javascript code	
	ret_flag = obj.value;
//    alert(ret_flag);

}


</script>

login_valid.php

<?php
include_once("functions_main.inc");

include_once("functions_main.inc");
$trow = chk_user($_GET['user_name']);
if ($trow == 1)
{
    $t1 = "Valid";
}
else 
{
    $t1 = "Invalid";	
}
echo "obj.value='$t1';\n";

?>
Here in above code my ret_flag variable in login_action is not getting available to my val_login() and return conditionally so that page does not change and let user change the values and resubmit if it wrong. The values login_valid.php is echoing is correct i did test it usign alert in login_action after ret_field assignment. But when it executes the if ... in login_valid the value is not getting updated.

I think it executes the login_valid that code before, so please guide me or suggest other alternate.

Thanks & Regards,

Naimesh Trivedi


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

1. You call your validation function "val_login".
2. It sends AJAX request to "login_valid.php".
3. While the AJAX and login_valid.php are proccesing, you check the ref_flag. Obviously ref_flag != "Valid" because your AJAX request is not competed yet, and there is no call to login_action().
4. Your validation function returns false ...

and finaly 5. Your AJAX request is ciompleted and to login_action() is called.

I have one question - why you want to use AJAX in this case?
There are 10 types of people in this world, those who understand binary and those who don't
nbt725
Forum Newbie
Posts: 11
Joined: Thu Aug 16, 2007 6:08 am

Post by nbt725 »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


[quote="VladSun"]1. You call your validation function "val_login".
2. It sends AJAX request to "login_valid.php".
3. While the AJAX and login_valid.php are proccesing, you check the ref_flag. Obviously ref_flag != "Valid" because your AJAX request is not competed yet, and there is no call to login_action().
4. Your validation function returns false ...

and finaly 5. Your AJAX request is ciompleted and to login_action() is called.

I have one question - why you want to use AJAX in this case?[/quote]

Dear Sir,


Hello ! Yes I know that is what happens, but how to execute the response and make user not refresh the page but to change the wrong info and we give message to user about this. I am open to other solution, if any. The ajax.js has got response object also I guess that would help but I don't know how to use it. Followong is my ajax.js

[syntax="javascript"]

ajax.js code

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 = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}


Thanks & Regards,

Naimesh Trivedi


feyd | Please use[/syntax]

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

AJAX solutions are often easier when usng a javascript library.. Jquery and prototype are two which I can name off the top of my head. Once you understand how they work it should be no trouble to get what you require working. A useful link for the background of AJAX (without using a variable) is XMLHttp tutorial (who's online example).

The easiest way to process the login and to tell if the login is correct or not is to simply return an empty string when the login is sucessful. If you need to redirect after the login is successful you need to test the length of the string, check if the length is 0 and do a javascript redirect.

What about people without javascript ?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

I don't think that AJAX should be used for this kind of "validation" - because it s not a FORM validation it is a log in validation. I am not sure what are you trying to achieve... It would be helpful if you post more code - especially for the FORM you are validating and the script which is called after successful log in...
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply