Solved

Javascript / Classic ASP / AJAX Form Submission

Posted on 2014-03-12
5
1,487 Views
Last Modified: 2014-04-03
I'm trying to create a dropdown box that, when selected, populates another dropdown box.  Then, submit the whole form and store the entered data in a database.  Sounds reasonably simple, I hope.

Below is what I have so far ALMOST works - but the "activated"/"populated" drop down value isn't being saved when the submit button is clicked.

The relevant code is found below and a SLIGHTLY modified version of the page can be found here: http://servicedesk.multiverseenterprises.net/livenewdevissue.asp (It's modified so it will show you the constructed SQL statement and NOT actually submit the data so you can see what's happening).

And on a separate note - for 100 bonus points each (basically, I'll increase the point value by 100 for each of the following two sub questions which I consider minor):

1. look through the code and note first: Lines 18-24 MUST be where they are in the code or the javascript won't activate the second dropdown - this is bizarre to me.  Can anyone explain why I can't move those lines to be IMMEDIATELY below line 62 (the one that reads: "'***************** PRE-OUTPUT CODE"

2. Why is it that I cannot use an object name of "Connect" instead of "conn" for the object that instantiates the database (lines 26-34).  Normally I prefer using "Connect" but for some reason, if I rename ALL instances of conn to Connect, then the same problem occurs where I can select the item in the first drop down but the second one fails to activate.

(By the way, I think ONLY the "project" ServiceDesk has data available to fill the second drop down).

(and let me say, AJAX/Javascript is NOT my area of expertise but I'd like to think I'm pretty good at Classic ASP).

So to recap:
1: for 300 points - Why isn't the form passing ItemID through on the reload so I can save in the database?
2: for 100 points - if you want them - why must the code in lines 17-24 be where it is?
3: for 100 points - if you want them - why can't I use "Connect" instead of "conn"?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@LANGUAGE="VBSCRIPT"%>
<!--#include virtual="/includes/init-asp-inc.asp"-->
<%
'***************** VARIABLE DECLARATIONS
Dim ProjectID, ItemID
'***************** VARIABLE PRESETS
DateEntered = Now()
PageName = "New Development Issue"
ProjectID = -1
ItemID = -1
'***************** FUNCTIONS
'***************** SUB ROUTINES
'for AJAX stuff to work, these two if blocks must be here.
If Len(Request("ProjectID")) > 0 And IsNumeric(Request("ProjectID")) Then
	ProjectID = CInt(SQLize(Request("ProjectID")))
End If

If Len(Request("ItemID")) > 0 And IsNumeric(Request("ItemID")) Then
	ItemID = CInt(SQLize(Request("ItemID")))
End If

'for AJAX stuff to work, database connection must be "conn"
Set conn=Server.CreateObject("ADODB.Connection")
conn.Open DBProvider 'as set in Init-asp-inc.asp

If Request("method") = "ajax" Then
	Call ShowItems(ProjectID)
	conn.Close()
	Response.End()
End If

Sub ShowItems(ProjID)

	Response.Write "<select name=""ItemID"" onchange=""this.form.submit()"""
	If ProjID = -1 Then Response.Write " disabled"
	Response.Write ">" & vbCRLF
	
	Response.Write "<option value=""-1"">---SELECT"
	If ProjID = -1 Then Response.Write " PROJECT FIRST"
	Response.Write "---</option>" & vbCRLF

	If ProjID > 0 Then
		SQL = "SELECT ItemID AS 'ID', ItemDesc FROM DevItems WHERE DevProject = " & ProjectID & " ORDER BY ItemDesc"
		Set DBRS = Connect.Execute(SQL)

		Do Until DBRS.EOF
			Response.Write vbTab & "<option value=""" & DBRS("ID") & """>" & DBRS("ItemDesc") & "</option>" & vbCRLf 
			DBRS.MoveNext
		Loop
	End If

	Response.Write "</select>" & vbCRLF
	Response.Write "<noscript><input type=""submit"" name=""ShowItemsDetails"" value=""Get Model Details"""
	If ProjID = -1 Then Response.Write " disabled"
	Response.Write "></noscript>"
End Sub

'***************** PRE-OUTPUT CODE
If Request.QueryString("action") = "save" Then
	SQL = "INSERT DevIssues (EnteredBy, DevItem, Project, Status, Summary, IssueDetail, IssueType, Priority) VALUES ("
	SQL = SQL & Session("UID") & ", " & ItemID & ", " & ProjectID & ", 65, '" & SQLize(Request.Querystring("summary")) 
	SQL = SQL & "', '" & SQLize(Request.QueryString("issuedetail")) & "', " & SQLize(Request.QueryString("issuetype"))
	SQL = SQL & ", " & SQLize(Request.QueryString("priority")) & ")"
	
	'Validate fields contain required data before attempting to submit.
	If IsNumeric(Request.QueryString("priority")) = False Or Len(Request.QueryString("priority")) < 1 Then
		ErrType = 1
		ErrMsg = ErrMsg & "A valid priority must be entered."
	End If
	
	If Len(Request.QueryString("Summary")) < 5 Then
		ErrType = 1
		ErrMsg = ErrMsg & "A valid summary was not entered."
	End If
	
	If Len(Request.QueryString("IssueDetail")) < 5 Then
		ErrType = 1
		ErrMsg = ErrMsg & "A detailed description must be provided."
	End If
	
	If IsNumeric(Request.QueryString("IssueType")) = False Then
		ErrType = 1
		ErrMsg = ErrMsg & "An issue type must be specified."
	End If
	
	If ProjectID = -1 Then
		ErrType = 1
		ErrMsg = ErrMsg & "A Project must be selected."
	End If
	
	If ItemID = -1 Then
		ErrType = 1
		ErrMsg = ErrMsg & "An item must be selected." & VbCrLf & "ItemID = " & Request.QueryString("ItemId")
	End If
	
	If ErrType = 0 Then
		Connect.Execute(SQL)
		Session("Message") = "Issue """ & Request.QueryString("summary") & """submitted successfully."
	Else
		Session("ErrMsg") = "Unable to save; " & ErrMsg
	End If
End If
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--#include virtual="/includes/head-inc.asp"-->
<link href="/css/menu.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">

/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var loadedobjects = "";
var rootdomain = "http://" + window.location.hostname;

function ajaxpage(url, containerid){
var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
		catch (e){}
		}
	}
	else
		return false
		
		page_request.onreadystatechange = function(){
		loadpage(page_request, containerid);
	}

	page_request.open('GET', url, true);
	page_request.send(null);
}

function loadpage(page_request, containerid){
	if(page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)){
		document.getElementById(containerid).innerHTML = page_request.responseText;
	}
}

/***Combo Menu Load Ajax snippet**/
function ajaxcombo(selectobjID, loadarea){
var selectobj = document.getElementById ? document.getElementById(selectobjID) : ""
	if(selectobj != "" && selectobj.options[selectobj.selectedIndex].value != ""){
		url = '<%=Request.ServerVariables("SCRIPT_NAME")%>?method=ajax&ProjectID=' + selectobj.options[selectobj.selectedIndex].value;
		ajaxpage(url, loadarea);
	}
}
</script>
</head>

<body>
<div id="Menu">
<!--#include virtual="/includes/menu-inc.asp"-->
</div><!-- /div id="Menu" -->

<div id="main"><!-- Main Section Below -->
<p class="PageTitle">
<% =PageName %>
</p>
<!--#include virtual="/includes/showmessages-inc.asp"-->
<table>
<form name="newdevissue" method="get" action="<%=Request.ServerVariables("SCRIPT_NAME")%>">
	<input type="hidden" name="action" value="save" />
	<tr>
		<td class="FieldName">Project:</td>
		<td class="FieldData"><select name="ProjectID" id="ProjectID" onchange="ajaxcombo('ProjectID','content_model')">
			<option value="-1">---SELECT PROJECT---</option>
			<%
			SQL = "SELECT ProjectID AS 'ID', ProjectName, Version FROM DevProjects WHERE SubscriberID = " & Session("SID") & " ORDER BY ProjectName"
			Set DBRS = Connect.Execute(SQL)
	
			Do Until DBRS.EOF
				Response.Write vbTab & "<option value=""" & DBRS("ID") & """>" & DBRS("ProjectName") 
				If IsNull(DBRS("Version")) = False Then Response.Write " v" & Trim(DBRS("Version"))
				Response.Write "</option>" & vbCRLf 
				DBRS.MoveNext
			Loop
			%>
			</select></td>
			<noscript><input type="submit" name="ShowItems" value="Set Project"></noscript>
	</tr>
	<tr>
		<td class="FieldName">Issue with:</td>
		<td><span id="content_model"><%Call ShowItems(ProjectID)%></span> <a href="adddevitem.asp?referURL=newdevissue.asp">New</a></td>
	</tr>
	<tr>
		<td class="FieldName">Type:</td>
		<td class="FieldData"><select name="issuetype">
			<option value="null">---SELECT---</option>
			<%
			SQL = "SELECT CatID AS 'ID', LongDesc FROM Categories WHERE Type = 'DvIssType' ORDER BY Ordering"
			Set DBRS = Connect.Execute(SQL)
			Do Until DBRS.EOF
				Response.Write vbTab & "<option value=""" & DBRS("ID") & """>" & DBRS("LongDesc") & "</option>" & vbCRLf 
				DBRS.MoveNext
			Loop
			%>
			</select>
		</td>
	</tr>
	<tr>
		<td class="FieldName">Summary:</td>
		<td class="FieldData"><input type="text" name="summary" size="50" maxlength="75" /></td>
	</tr>
	<tr valign="top">
		<td class="FieldName">Detail:</td>
		<td class="FieldData"><textarea name="issuedetail" cols="70" rows="8" wrap="virtual"></textarea></td>
	</tr>
	<tr>
		<td class="FieldName">Priority:</td>
		<td class="FieldData"><input type="text" name="priority" size="3" maxlength="3" /></td>
	</tr>
	<tr>
		<td colspan="2" align="right"><input type="submit" value="Save"></td>
	</tR>
	</form>

	<% conn.Close %>

</table>

<!-- /div id="" Main Section -->
<!--#include virtual="/includes/publicfooter-inc.asp"-->
<%
'***************** CLOSING CODE
%>
<!--#include virtual="/includes/codefooter-inc.asp"-->

Open in new window

0
Comment
Question by:Lee W, MVP
  • 2
  • 2
5 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 300 total points
ID: 39923122
1: for 300 points - Why isn't the form passing ItemID through on the reload so I can save in the database?

Because your page is malformed. Check the following picture :
maformed
As you can see, your form is empty, the childrend of your table is not thead or tbody or at least row so you get strange issues.

GO here to validate your HTML : http://validator.w3.org/
You must correct all errors before starting programming.
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39923388
If you want to use multiple drop downs, I like to send all the data to the browser at once and use javascript/jquery to do the work.  I have had good success with chained http://www.appelsiini.net/projects/chained.

From the sample code, you can see the value in the first select will match the class of the 2nd.   This is very easy to implement and no 2nd or 3rd trips to the DB.

<select id="mark" name="mark">
  <option value="">--</option>
  <option value="bmw">BMW</option>
  <option value="audi">Audi</option>
</select>
<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" class="bmw">3 series</option>
  <option value="series-5" class="bmw">5 series</option>
  <option value="series-6" class="bmw">6 series</option>
  <option value="a3" class="audi">A3</option>
  <option value="a4" class="audi">A4</option>
  <option value="a5" class="audi">A5</option>
</select>

Open in new window


2) I have not gone through the code, but that range is only checking to see if request("ItemID") is a number.  Personally, I would have done it like this because you will avoid errors when the form or querystring is bad.  It is also bad practice to use just request and instead use request.querystring or request.form.

If Len(Request("ItemID")) <> "" then
    if IsNumeric(Request("ItemID")) Then
    ' we have a good item id
    end if
end if

Open in new window


3) Probably because your connection string was built using conn.   It is the same as asking why if x=3, how come you are not getting the same value for Y.  There is only one connectionstring per db you are using.
0
 
LVL 95

Author Comment

by:Lee W, MVP
ID: 39924186
Scott,

I don't want to send all the data to the form because it COULD be a LOT of data and it could find people who shouldn't necessarily be seeing that data getting it (the sharper ones could look at the source).

It is also bad practice to use just request and instead use request.querystring or request.form.

I agree - if you review the rest of the code, MOST places use Request.Querystring (or Request.Form) - the areas that say "request()" are what was in the original code snippet I incorporated for the Javascript (to get this working as far as I did I had to do a lot of trial and error and though my original attempt had corrected that, my subsequent try did not).

Probably because your connection string was built using conn.   It is the same as asking why if x=3, how come you are not getting the same value for Y.  There is only one connectionstring per db you are using.

I think one of use  is confused.  (COULD DEFINITELY BE ME).  I Originally did a find/replace so that EVERY instance of "conn" was replaced with "Connect" - shouldn't that resolve it?  MY code always uses "Connect" (it's just the way I've done things for years and I'd like to keep consistent) and the ONLY place (in the included files or in this one) that "conn" exists is in this document - which, by my logic, SHOULD be easily changeable provided I change it everywhere... but that doesn't seem to be the case.

@leakim971
I try to keep things reasonably clean but I AM still coding with what I know which hasn't necessarily increased all that much over the years in terms of HTML development.  So it's possibly I've made some errors - I'll run it through that web page and see what I get.  Thanks.
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39924238
>I Originally did a find/replace so that EVERY instance of "conn"

Are you using an include for for your connection?  maybe the include file needs to be changed?

I will not be able to respond the rest of the day.  But you could use ajax for the 2nd select and I know leakim can get that part going for you.  It's the same idea as what I presented but the data for the 2nd select is not generated until the first changes.
0
 
LVL 95

Author Closing Comment

by:Lee W, MVP
ID: 39977306
Thanks,

When I ran things through http://validator.w3.org/ I found many issues and upon correcting them, the issue resolved itself.


Still don't know why the ASP has issues, but that was a minor thing for me.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
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…

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now