Solved

How do I check  in classic ASP the existence of a record on a Database using Javascript to prevent duplicates

Posted on 2008-10-22
5
794 Views
Last Modified: 2008-11-14
This is my current form which posts to succeedpayment.asp
<% 
level="../"
 
if (Request.Form("Submit")="") then
%>
<!-- #include file="session_destroy.asp"-->
<%end if%>
 
<!--#include file="../include/intialize.inc"-->
<!--include file="../include/connection.asp"-->
<!--#include file="../../Connections/sqlConn1.asp" -->
 
<!-- Include file for CAPTCHA configuration -->
<!-- #include file="CAPTCHA/CAPTCHA_configuration.asp" -->
 
 
 
<html>
<head>
<title><%=PageTitle%></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../style/style.css" rel="stylesheet" type="text/css">
 
<script type="text/javascript">
<!--
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- email field must contain a valid e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- zip code field must contain only numbers.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
 
function YY_checkform() { //v4.66
//copyright (c)1998,2002 Yaromat.com
  var args = YY_checkform.arguments; var myDot=true; var myV=''; var myErr='';var addErr=false;var myReq;
  for (var i=1; i<args.length;i=i+4){
    if (args[i+1].charAt(0)=='#'){myReq=true; args[i+1]=args[i+1].substring(1);}else{myReq=false}
    var myObj = MM_findObj(args[i].replace(/\[\d+\]/ig,""));
    myV=myObj.value;
    if (myObj.type=='text'||myObj.type=='password'||myObj.type=='hidden'){
      if (myReq&&myObj.value.length==0){addErr=true}
      if ((myV.length>0)&&(args[i+2]==1)){ //fromto
        var myMa=args[i+1].split('_');if(isNaN(myV)||myV<myMa[0]/1||myV > myMa[1]/1){addErr=true}
      } else if ((myV.length>0)&&(args[i+2]==2)){
          var rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-z]{2,4}$");if(!rx.test(myV))addErr=true;
      } else if ((myV.length>0)&&(args[i+2]==3)){ // date
        var myMa=args[i+1].split("#"); var myAt=myV.match(myMa[0]);
        if(myAt){
          var myD=(myAt[myMa[1]])?myAt[myMa[1]]:1; var myM=myAt[myMa[2]]-1; var myY=myAt[myMa[3]];
          var myDate=new Date(myY,myM,myD);
          if(myDate.getFullYear()!=myY||myDate.getDate()!=myD||myDate.getMonth()!=myM){addErr=true};
        }else{addErr=true}
      } else if ((myV.length>0)&&(args[i+2]==4)){ // time
        var myMa=args[i+1].split("#"); var myAt=myV.match(myMa[0]);if(!myAt){addErr=true}
      } else if (myV.length>0&&args[i+2]==5){ // check this 2
            var myObj1 = MM_findObj(args[i+1].replace(/\[\d+\]/ig,""));
            if(myObj1.length)myObj1=myObj1[args[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!myObj1.checked){addErr=true}
      } else if (myV.length>0&&args[i+2]==6){ // the same
            var myObj1 = MM_findObj(args[i+1]);
            if(myV!=myObj1.value){addErr=true}
      }
    } else
    if (!myObj.type&&myObj.length>0&&myObj[0].type=='radio'){
          var myTest = args[i].match(/(.*)\[(\d+)\].*/i);
          var myObj1=(myObj.length>1)?myObj[myTest[2]]:myObj;
      if (args[i+2]==1&&myObj1&&myObj1.checked&&MM_findObj(args[i+1]).value.length/1==0){addErr=true}
      if (args[i+2]==2){
        var myDot=false;
        for(var j=0;j<myObj.length;j++){myDot=myDot||myObj[j].checked}
        if(!myDot){myErr+='* ' +args[i+3]+'\n'}
      }
    } else if (myObj.type=='checkbox'){
      if(args[i+2]==1&&myObj.checked==false){addErr=true}
      if(args[i+2]==2&&myObj.checked&&MM_findObj(args[i+1]).value.length/1==0){addErr=true}
    } else if (myObj.type=='select-one'||myObj.type=='select-multiple'){
      if(args[i+2]==1&&myObj.selectedIndex/1==0){addErr=true}
    }else if (myObj.type=='textarea'){
      if(myV.length<args[i+1]){addErr=true}
    }
    if (addErr){myErr+='* '+args[i+3]+'\n'; addErr=false}
  }
  if (myErr!=''){alert('The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+myErr)}
  document.MM_returnValue = (myErr=='');
}
//-->
</script>
 
<script language="JavaScript">
<!--
function isAlpha ( evt ) {
   var keyCode = evt.which ? evt.which : evt.keyCode;
   alpha = ( keyCode >= 'a'.charCodeAt ( ) &&
      keyCode <= 'z'.charCodeAt ( ) ) || 
      ( keyCode >= 'A'.charCodeAt ( ) &&
      keyCode <= 'Z'.charCodeAt ( ) ) || 
      ( keyCode >= 8 && keyCode <= 46 );
   return ( alpha );
}
 
function validateAlpha ( text ) {
   for ( c=0; c < text.length; c ++ ) {
      alpha = ( text.charCodeAt ( c ) >= 65 &&
         text.charCodeAt ( c ) <=90 ) || 
         ( text.charCodeAt ( c ) >= 97 &&
         text.charCodeAt ( c ) <=122 )
      if ( !alpha ) {
         alert ( 'No way, sorry.' );   
         document.theForm.theField.select ( );
         return false;
      }
   }
   return true;
}
//-->
</script>
</head>
 
<%
' Memeber Registration 
	if (Request.Form("Submit")<>"") then
	
	'Select all of the records and compare with new username
set rs9 = Server.Createobject("ADODB.Recordset")
SQL = "SELECT * FROM Players WHERE Email = '"&Email&"'"
rs9.open sql,conSQL
If conSQL.Execute(SQL).EOF Then
'   Not in the database
'   Add it to the database
	
		txtuname=request.form("txtuname")
		
			session("S_txtfname")=request.form("txtfname")
			session("S_txtlname")=request.form("txtlname")
			session("S_txtaddr1")=request.form("txtaddr1")
			session("S_txtaddr2")=request.form("txtaddr2")
			session("S_txtcity")=request.form("txtcity")
			session("S_txtstate")=request.form("txtstate")
			session("S_txtcourseid")=request.form("txtcourseid")
			session("S_txtpcode")=request.form("txtpcode")
			session("S_txtcontactno")=request.form("txtcontactno")
			session("S_txtemailid")=request.form("txtemailid")
			session("S_txtuname")=request.form("txtuname")
			session("S_txtpwd")=request.form("txtpwd")
 
			'response.redirect "RegistrationStep-2.asp"
			'response.redirect "succeedpayment.asp"
				
		else 
		%>
			<script language='Javascript'>
		  		alert('Email Already Exists, Try Again....') 
				history.go(-1)	
			</script>
			<%
		end if
		end if 
%>

Open in new window

0
Comment
Question by:RickyGtz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 7

Accepted Solution

by:
alexpercsi earned 250 total points
ID: 22780390
Instead of selecting the whole list of usernames and comparing it in asp with the new username, consider sending the username to the database and counting the rows where it matches. If the result is greater than 0 then the username already exists.

SQL = "SELECT Count(*) FROM Players WHERE Email = '"&Email&"'"

The result will be a single row with a single cell. If the value inside is zero, the email does not exist in the database.

I hope this helps.

Best Regards,
Alex Percsi.
0
 

Author Comment

by:RickyGtz
ID: 22780460
Well the thing is that is working if I dont put in form Action= " Page2"    but when I do it doesnt catch the error ,, I want to put this on page 2 I guess ..

0
 
LVL 7

Expert Comment

by:alexpercsi
ID: 22781619
If you put Action="page2" on the form the server side code will no longer execute in this page. Rather, the posted form will be handled by "Page2". Indeed, you need to move the code to Page2. As an alternative, you can leave Page1 as the action for the form and redirect to page 2 from the server side using Response.Redirect. This however will make the form data unavailable in page2, so make sure you process it before redirecting.
0
 

Author Comment

by:RickyGtz
ID: 22781749
i understand, so, how can i detect duplicate usernames, emails for the values posted to it on a page2 quering the database, the current implementation would just not do it..

this is page2 (called succeedpayment) in which page 1 is posted to

 
<% response.buffer=true
 level="../"%>
 
<!--include file="../include/connection.asp"-->
<!--#include file="../../Connections/sqlConn1.asp" -->
<!--#include file="../../Connections/sqlConn3.asp" -->
<!--#include file="rc4.inc"-->
 
 
<!-- Include file for CAPTCHA form processing -->
<!-- #include file="CAPTCHA/CAPTCHA_process_form.asp" -->    
<!-- Include file for CAPTCHA configuration -->
<!-- #include file="CAPTCHA/CAPTCHA_configuration.asp" -->
      
<%
 
' If "" & Request("txtemailid") <> "" Then
    'If Trim(Request("txtemailid")) <> "" Then 
    If blnCAPTCHAcodeCorrect <> True then
       'Place code here that is to run if CAPTCHA is NOT entered correctly
	   
	   Response.Write("CAPTCHA code is NOT correct")
	   Response.Redirect "index.asp?err=captcha"
	End If
	
			' Generating Random Number 
		set RecsetRef= conSQL.execute("select max(referenceno) from Players")
		
		If isnull(RecsetRef(0)) Then 
			ReferenceNumber=1001
		else
			S_ReferenceNumber =  RecsetRef(0)
			ReferenceNumber=S_ReferenceNumber+1
		End If
		RecsetRef.close
		Set RecsetRef = Nothing 
		Response.Write(ReferenceNumber)
 
'		psw="playerscores"	
'		stime = timer
'		strTemp = EnDeCrypt(ReferenceNumber, psw)
 
		' Retrieving from the Sigup form
		session("S_txtfname")= request.form("txtfname")
		session("S_txtlname") = request.form("txtlname")
		session("S_txtaddr1")= request.form("txtaddr1")
		session("S_txtaddr2")=request.form("txtaddr2")
		session("S_txtcity") = request.form("txtcity")
		session("S_txtstate")=request.form("txtstate")
		'session("S_optcountry")
		session("S_txtpcode") =request.form("txtpcode")
		session("S_txtcourseid")=request.form("txtcourseid") 
		session("S_txtmemberid")=request.form("txtmemberid")
		session("S_txtcontactno")=request.form("txtcontactno")
		session("S_txtemailid")=request.form("txtemailid")
		session("S_txtuname") =request.form("txtuname")
		session("S_txtpwd")=request.form("txtpwd")	
		
		
		txtfname=session("S_txtfname")
		txtlname=session("S_txtlname")
		txtaddr1=session("S_txtaddr1")
		txtaddr2=session("S_txtaddr2")
		txtcity=session("S_txtcity")
		txtstate=session("S_txtstate")
		optcountry=session("S_optcountry")
		txtpcode=session("S_txtpcode")
		txtcourseid=session("S_txtcourseid")
		txtmemberid=session("S_txtmemberid")
		txtcontactno=session("S_txtcontactno")
		txtemailid=session("S_txtemailid")
		txtuname=session("S_txtuname")
		txtpwd=session("S_txtpwd")
		
		regdate=date()
		regtime=time()
		
		
'catching if email and username already taken ... 
 
 
sql7 = " Select Email from Players Where Email = '" & Request.Form("txtemailid") & "'"
 
'" & Request.Form("desiredUserName") 
set rs7 = Server.Createobject("ADODB.Recordset")
set rs7=conSQL.execute(sql7)
if not rs7.EOF then %>
 
<script language='Javascript'>
	alert('The Enter E-Mail already exist on our database , please enter a different e-mail ....'); 
						history.go(-1);
						</script>	
<% End If %>
<%
 
		'toaddress = Request.Form("recipient")
  		'.To = "&toaddress&"
					
		txtuname=request.form("txtuname")
		set rs = Server.Createobject("ADODB.Recordset")
		sql = "select * from Players where SSN='"&txtuname&"'"
		rs.open sql,conSQL
		if rs.BOF then 
		set rs2 = Server.Createobject("ADODB.Recordset")
		sql1 = "select count(*) as memcon from Players where courseID="&txtcourseid&" and memberid='"&txtmemberid&"'"
		sql11 = "select count(*) as memcon from Players where courseID="&txtcourseid&" and Email='"&txtemailid&"'"
		set rs2=conSQL.execute(sql1)
		set rs2=conSQL.execute(sql11)
		if rs2("memcon") <> 0 then	%>
			
			
	<script language='Javascript'>
	alert('The Member Id in the selected course is Already Exists, Try Again....'); 
						history.go(-1);
						
					</script>
		<%	else	
		  	'response.redirect "succeedpayment.asp"
			end if		
		else 
		%>
        
			<script language='Javascript'>
		  		alert('Username Already Exists, Try Again....') 
				history.go(-1)	
			</script>
			<%		
		end if
		'rs2.close
		'set rs2=nothing
	rs.close
	set rs = nothing 
	'end if	
		
	
		on error resume next
		
conSQL.execute("Insert into Players(SSN,[password],firstname,lastname,addy1,addy2,city,state,Zip,phone,email,regdate,regtime,referenceno,courseid,memberid) values('"&txtuname&"','"&txtpwd&"','"&txtfname&"','"&txtlname&"','"&txtaddr1&"','"&txtaddr2&"','"&txtcity&"','"&txtstate&"',"&txtpcode&","&txtcontactno&",'"&txtemailid&"','"&regdate&"','"&regtime&"',"&ReferenceNumber&","&txtcourseid&",'"&txtmemberid&"')")
 
'response.write("Insert into Players(SSN,[password],firstname,lastname,addy1,addy2,city,state,Zip,phone,email,regdate,regtime,referenceno,courseid,memberid) values('"&txtuname&"','"&txtpwd&"','"&txtfname&"','"&txtlname&"','"&txtaddr1&"','"&txtaddr2&"','"&txtcity&"','"&txtstate&"','"&txtpcode&"',"&txtcontactno&",'"&txtemailid&"','"&regdate&"','"&regtime&"',"&ReferenceNumber&","&txtcourseid&",'"&txtmemberid&"')")
 
 
 
		If Err.Number <> 0 Then
		Response.Write "Error: " & Err.Description
			    response.end
			Response.Write "Unable to Store your Information "
		response.end
		else
		    session("username")=txtuname
			session("txtemailid") = txtemailid
			
'Send Mail with CDOSYS
 
sql="<html><body><b>Dear Member,</b><br><br>  Your account information has Been verified by playerscores.com staff.<br>Your account has been activated. <br><br>Your Username - "&txtuname&"<br>Your Password - "&txtpwd&" <br><br> Important information - Please write down this reference # to edit your <br> account with www.playerscores.com/ <br>  Your Reference Number is :"&ReferenceNumber&" <br> <br>  To Confirm your membership click on the link below,<br><a href='http://www.playerscores.com/members/verify.asp?refno="&ReferenceNumber&"'>http://www.playerscores.com/members/verify.asp?refno="&ReferenceNumber&"</a><br><br> <BR>  Please don't hesitate to email us if any questions should arise. <br><BR>  Thanks,<BR>  Playerscores staff<BR>  info@playerscores.com</body></html>"
 
	
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Thanks For your Registration with Playerscores.com "
myMail.From="info@playerscores.com"
myMail.To= txtemailid
myMail.HTMLBody= sql
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
="192.168.5.235"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") _
=25 
myMail.Configuration.Fields.Update
myMail.Send
If Err.Number <> 0 Then
				Response.Write "Error: " & Err.Description
			    response.end
			    end if
				
				' clean up 
				set myMail=nothing
 
 
 
	' Insert newly registered member into Mailing list		
		Randomize Timer
		'Calculate a code for the user
		strUserCode = Left(txtemailid,2) & (9876989856 * CInt((RND * 32000) + 100))
 
		con3SQL.Execute("insert into tblMailingList (Email,ID_Code) values('"&txtemailid&"','"&	        strUserCode&"')")		
		'con7.execute("update tblauthor set Active = 1 where username='"&request("SSN")&"'")
		
	'response.redirect "../Forum/register.asp?mode=new"	
	
		response.redirect "thank.asp"
	
	
		end if
%>

Open in new window

0
 

Author Comment

by:RickyGtz
ID: 22787656
Hi It is not launching the script..
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

717 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