How to do button action in ASP? - asp-classic

I am new to ASP. I need to insert values into database using ASP on clicking on submit button.
How to do that I do know.
My Code Is:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include file="connection.asp"-->
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form</title>
</head>
<form name="form1" id="form1" method="post" onsubmit="return validate()">
<h3>FORM</h3>
<table align="center" cellpadding = "10">
<tr>
<td>Name</td>
<td><input type="text" name="uname" id="uname" /></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="umobile" id="umobile" maxlength="10" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="uemail" id="uemail" /></td>
</tr>
<tr>
<td>Residing City
<td><input type="text" name="rescity" id="rescity" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
<body>
<%
uname = request.Form("uname")
umobile = request.Form("umobile")
uemail = request.Form("uemail")
city = request.Form("city")
set rs = Server.CreateObject("ADODB.Recordset")
Qry = "INSERT INTO enquirydetails([name],[mobile],[email],[residingcity]) values ('"&(uname)&"','"&(umobile)&"','"&(uemail)&"','"&(city)&"')"
rs.OPEN Qry,Conn
%>
</body>
</html>
Using this code if I go to that page the values getting inserted as blank.
Please give me any Suggestions.

Because there is no check to see whether the data in your form has been submitted the code to insert a new record is running whenever the page is loaded.
Usually the way to approach this is check the length Request.Form to see if any form parameters have been submitted. Something like this should fix your code;
<%
If Len(Request.Form) > 0 Then
uname = request.Form("uname")
umobile = request.Form("umobile")
uemail = request.Form("uemail")
city = request.Form("city")
set rs = Server.CreateObject("ADODB.Recordset")
Qry = "INSERT INTO enquirydetails([name],[mobile],[email],[residingcity]) values ('"&(uname)&"','"&(umobile)&"','"&(uemail)&"','"&(city)&"')"
rs.OPEN Qry,Conn
End If
%>
There is still a problem however and that is with the approach to the INSERT. By dynamically assigning values directly to the SQL string you are leaving the application open to SQL Injection which is a common attack aimed at web applications with unsecured calls to a database back-end.
ADO provides a useful object called ADODB.Command which helps us with this by building parametrised queries, here is an example of how to replace your existing code;
<%
Dim cmd, sql
If Len(Request.Form) > 0 Then
uname = request.Form("uname")
umobile = request.Form("umobile")
uemail = request.Form("uemail")
city = request.Form("city")
Set cmd = Server.CreateObject("ADODB.Command")
sql = "INSERT INTO enquirydetails([name],[mobile],[email],[residingcity]) VALUES (?, ?, ?, ?)"
With cmd
.ActiveConnection = Conn 'Assuming this is your connection string
.CommandType = adCmdText
.CommandText = sql
'Create Parameters and append them in order
.Parameters.Append(.CreateParameter("#name", adVarWChar, adParamInput, 255))
.Parameters.Append(.CreateParameter("#mobile", adVarWChar, adParamInput, 255))
.Parameters.Append(.CreateParameter("#email", adVarWChar, adParamInput, 255))
.Parameters.Append(.CreateParameter("#residingcity", adVarWChar, adParamInput, 255))
'Assign values to the parameters
.Parameters("#name").Value = uname
.Parameters("#mobile").Value = umobile
.Parameters("#email").Value = uemail
.Parameters("#residingcity").Value = city
.Execute()
End With
Set cmd = Nothing
End If
%>
NOTE: If you have problems with this code it is likely the use of Named Constants (adCmdText etc) to fix this see this article which describes how to use Named Constants.

Related

In Classic ASP "On Button Click " Data in the text boxes need to post to the Stored Procedure Parameters

I designed an classic ASP application. In that i need to search the Employee Details by clicking Search Button. But it was not happening.
My ASP Page Code:
<html>
<head>
<title>Nothwind Employees Details</title>
</head>
<body bgcolor="white" text="black">
<form method="POST" action="EmpDetailsbySrch.asp">
<table border="0" align="center" cellpadding="8">
<tr>
<td>
Emp ID:
</td>
<td>
<input type="text" name="txtId" size="10" />
</td>
<td>
First Name:
</td>
<td>
<input type="text" name="txtFirstName" size="10" />
</td>
<td>
Last Name:
</td>
<td>
<input type="text" name="txtLastName" size="10" />
</td>
<td>
Employee Role:
</td>
<td>
<input type="text" name="txtTitle" size="10" />
</td>
<td>
City:
</td>
<td>
<input type="text" name="txtCity" size="10" />
<input type="submit" value="Search" onclick=""/>
</td>
</tr>
</table>
</form>
<%
Dim adoCon
Dim rsEmployees
Dim strSQL
EmpId = request.Form("txtId")
LastName = request.Form("txtLastName")
FirstName = request.Form("txtFirstName")
Role = request.Form("txtTitle")
City = request.Form("txtCity")
Set adoCon = Server.CreateObject("ADODB.Connection")
StrCnn = "Provider=SQLOLEDB.1;Password=Wissen#01;Persist Security Info=True;User ID=sa;Initial Catalog=NORTHWND;Data Source=WISBLR2410"
adoCon.Open StrCnn
strSQL = "EXECUTE [dbo].[USP_EmpDetbySrch]"
set rsEmployees = adoCon.Execute(strSQL)
Response.write "<table border='1' cellpadding='2' align='Center'>"
Response.write "<tr>"
dim field
For Each field in rsEmployees.Fields
Response.write "<th>" & field.Name & "</th>"
Next
Response.write "</tr>"
dim x : x = 0
Do While Not rsEmployees.EOF
Response.write "<tr>"
For Each field in rsEmployees.Fields
Response.write "<td>" & rsEmployees(field.Name) & "</td>"
Next
Response.write "</tr>"
x = x + 1
rsEmployees.MoveNext
Loop
Response.write "</table>"
adoCon.Close
Set adoCon = Nothing
%>
</body>
</html>
Stored Procedure with Parameters:
USE [NORTHWND]
GO
/****** Object: StoredProcedure [dbo].[USP_EmpDetbySrch] Script Date: 5/27/2016 2:35:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: SR
-- Create date: <25-May-2016>
-- Description: Get Employee Details of NORTHWIND DB
-- =============================================
ALTER PROCEDURE [dbo].[USP_EmpDetbySrch]
#EmpId int = NULL,
#FirstName nvarchar(20) = NULL,
#LastName nvarchar(10) = NULL,
#Role nvarchar(30) = NULL,
#City nvarchar(15) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT [EmployeeID]
,[LastName]
,[FirstName]
,[Title]
,[TitleOfCourtesy]
,[BirthDate]
,[HireDate]
,[Address]
,[City]
,[Region]
,[PostalCode]
,[Country]
,[HomePhone]
,[Extension]
FROM [dbo].[Employees]
WHERE [EmployeeID] = ISNULL(#EmpId,EmployeeID) OR [LastName] = ISNULL(#LastName,LastName) OR [FirstName] = ISNULL(#FirstName,FirstName)
OR [Title] = ISNULL(#Role,Title) OR [City] = ISNULL(#City,City)
END
I designed an classic ASP application. In that i need to search the Employee Details by clicking Search Button. But it was not happening. Please Suggest how to do this and where i went wrong.

Download Excel not working properly in ASP

I am new to ASP.I need to write a script for Download Excel in ASP.I tried but it is downloading the entire page content but I need to download the table from database.
Here is my code:
<%#Language="VBScript"%>
<form name="form1" id="form1" method="post">
<input type="hidden" name="action" value="sel">
<table>
<tr>
<td><input type="submit" name="submit" id="submit" value="Download Excel"></td>
</tr>
</table>
Hello World
<%
action = Request.Form("action")
If action="sel" Then
Response.ContentType = "application/octet-stream"
Response.ContentType = "application/vnd.ms-excel"
SET Conn = Server.CreateObject("ADODB.Connection")
Conn.OPEN "PROVIDER=SQLOLEDB;DATA SOURCE=10.1.1.1;UID=sa;PWD=root;DATABASE=Student"
dim Conn,Rs
set Rs=server.createobject("ADODB.recordset")
Rs.open "SELECT * FROM studentdetails",Conn
Response.AddHeader "Content-Disposition", "attachment; filename=xl_data.xls"
%>
<TABLE BORDER=1>
<TR>
<%
j = 2
For i = 0 to RS.Fields.Count - 1
%>
<TD width="18"><B>
<% = RS(i).Name %></B></TD>
<% Next %>
<TD width="42"></TD>
<TD width="53"></TD>
</TR>
<%
Do While Not RS.EOF
%>
<TR>
<% For i = 0 to RS.Fields.Count - 1
%>
<TD VALIGN=TOP><% = RS(i) %></TD>
<% Next %>
</TR>
<%
RS.MoveNext
j = j + 1
Loop
RS.Close
End If
%>
</TABLE>
In this program I have included Hello World line while downloading it is downloading that also.So Please give me some suggestions.THANKS IN ADVANCE.
replace
Response.ContentType = "application/octet-stream"
with
Response.Clear
otherwise you are sending the form and the table to Excel

Inserting SQL data for one table into an html table using ASP.net or Classic ASP

For a bit of background info I'm a Network Admin/Systems Admin with very very minimal self-taught programming 'skills'. In the past I have just modified and tweaked existing code to get whatever I was looking for to work but I'm not having any luck with this current project. I am looking to add dynamic prices from a sql table into an existing html table for only a few of the records that are in the sql table.
I'm using a locally hosted server using IIS6 with a mix of ASP.net 2.0 and classic asp on the site with a 2008 MS SQL Server database.
I already have the connection to the db made in global.asa and am looking for how I can correspond each price to each html item number in the table.
(the sql code I copy/pasted from a different asp file with different intentions so if something looks completely off its probably because of that :[ )
Ex:
<html>
<head>
<%
sql = "SELECT * FROM tblProductCatalogue WHERE ( (tblProductCatalogue.CustomerID = 1 ) and (tblProductCatalogue.ItemNumber = ItemNumber)) "
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open sql, conn, 3, 3
if NOT rs.eof then
rs.MoveFirst
DerivedPrice = rs("DerivedPrice")
rs.close
Set rs = Nothing
%>
</head>
<body>
<table>
<tr>
<th>Item Number</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<td>PartNumber1</td>
<td>description1</td>
<td><%DerivedPrice%></td>
</tr>
<tr>
<td>PartNumber2</td>
<td>description2</td>
<td><%DerivedPrice%></td>
</tr>
<tr>
<td>PartNumber3</td>
<td>description3</td>
<td><%DerivedPrice%></td>
</tr>
</table>
</body>
</html>
Thanks!
Stan
So close! You need a loop around your table rows. Replace your table with this:
if NOT rs.eof then rs.MoveFirst
'...remove this code from your exampl (above), snip---'
DerivedPrice = rs("DerivedPrice")
rs.close 'especially this code'
Set rs = Nothing 'and this code'
'---snip, end----'
%>
<%= rs.RecordCount %> Rows<br/> <!-- optional, for troubleshooting -->
<table>
<tr>
<th>Item Number</th>
<th>Description</th>
<th>Price</th>
</tr>
<%
While NOT rs.eof 'loop through the dataset'
%>
<tr>
<td><%= rs("PartNumber") %></td>
<td><%= rs("Description") %></td>
<td><%= rs("DerivedPrice") %></td>
</tr>
<%
rs.MoveNext
Wend 'end while
rs.close
Set rs = Nothing
%>
</table>

Creating a Table at the click of a button with classic asp

I am trying to validate information, without switching the page (in this case a username, if the username is found, great, populate a textbox and dynamically create a table with the username it it). However, I am getting an error on line 75 that reads:
ADODB.Recordset
error '800a0e78'
Operation is not allowed when the object is closed.
/login.asp, line 75
I haven't closed the recordset anywhere. By my knowledge it should work. What am I doing wrong?
<%
Dim cn,rs
Set cn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.recordset")
cn.Provider = "Microsoft.Jet.OLEDB.4.0"
cn.Open Server.MapPath("login.mdb")
'Default message for the user on the login page
msg = "Please login"
'Logout code. This code empties the session variable which holds the user's userID.
If Request.QueryString("action") = "logout" Then
Session("user_id") = ""
msg = "You have been logged out"
End If
'Check if the form has been submitted
If Request.Form("Submit") = "Test" Then
user_name = Request.Form("user_name")
user_pass = Request.Form("user_pass")
mySQL = "SELECT user_id, user_name, user_pass FROM users WHERE user_name = '" & user_name & "' AND user_pass = '" & user_pass & "'"
'Select the data from the database using the submitted data.
rs.Open mySQL, cn
'Check if a match was found.
If NOT rs.EOF Then
'Session("user_id") = rsLogin("user_id")
'Response.Redirect("profile.asp")
u = rs("user_name")
Else
'If a match was not found then output an error.
Response.Redirect("login.asp?errmsg=Login failed")
End If
End If
%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form1" id="form1" method="post" action="">
<table width="300" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Username</td>
<td><input name="user_name" type="text" id="user_name" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="user_pass" type="password" id="user_pass" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Test" /></td>
</tr>
</table>
</form>
<input id="fileno" value="<%=u%>" type="text">
<%
While NOT rs.EOF
%>
<table width="200" border="1" cellspacing="0" cellpadding="2">
<tr>
<th scope="col"><div align="left">username</div></th>
</tr>
<tr>
<td><%=u%></td>
</tr>
<%
rs.MoveNext
Wend
%>
</table>
</body>
</html>
When this condition fails.
If Request.Form("Submit") = "Test"
your code tries to access rs.eof without opening the recordset.
Put the rs.open OUTSIDE of that block.
Means you haven't closed your connection object
try set cn =Nothing at the end of your page

textarea text into sql column

If I use a textbox I have no issues getting data into sql. I'd like to use a textarea with autowrap and all that. But when I change the <input type="text" id="au_id"> to <textarea name="au_id"> I can't get the .value of au_id.Value code listed below.
All I want is to swap single line text box for multiline textarea and still onclick get my lines posted in sql. Some of the names/id's make no sense for what they go to, I copied most of the code from Microsoft's site, and making changes as I go.
code:
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Text"%>
<html>
<head>
<style type="text/css">
#au_id
{
height: 103px;
}
</style>
</head>
<script language="VB" runat="server" >
Dim MyConnection As SqlConnection
Sub Page_Load(Src As Object, e As EventArgs)
' Create a connection to the "EMR" SQL database located on
' the local computer.
MyConnection = New SqlConnection("server=localhost;" _
& "database=EMR;Trusted_Connection=Yes")
' Check whether this page is a postback. If it is not
' a postback, call a custom BindGrid function.
If Not IsPostBack Then
BindGrid()
End If
End Sub
' Implement an AddAuthor_Click function. This function does some data
' validation on the input form and builds a parameterized command containing
' all the fields of the input form. Then it executes this command to the
' database and tests (using the try command) whether the data was added.
' Finally, it rebinds the DataGrid to show the new data.
Sub AddAuthor_Click(ByVal Sender As Object, ByVal e As EventArgs)
Dim myCommand As SqlCommand
Dim insertCmd As String
If (au_fname.Value = "" Or au_lname.Value = "" _
Or phone.Value = "") Then
Message.InnerHtml = "ERROR: Null values not allowed for " _
& "Author ID, Name or Phone"
Message.Style("color") = "red"
BindGrid()
Exit Sub
End If
' Build a SQL INSERT statement string for all the input-form
' field values.
insertCmd = "insert into VisitData values (#Subjective, #Objective, #Assessment," _
& "#Plan, #HT, #WT, #BP, #ServiceDate, #Diagnosis);"
' Initialize the SqlCommand with the new SQL string.
myCommand = New SqlCommand(insertCmd, myConnection)
' Create new parameters for the SqlCommand object and
' initialize them to the input-form field values.
myCommand.Parameters.Add(New SqlParameter("#Subjective", _
SqlDbType.VarChar, 8000))
myCommand.Parameters("#Subjective").Value = au_id.Value
myCommand.Parameters.Add(New SqlParameter("#Objective", _
SqlDbType.VarChar, 8000))
myCommand.Parameters("#Objective").Value = au_lname.Value
myCommand.Parameters.Add(New SqlParameter("#Assessment", _
SqlDbType.VarChar, 8000))
myCommand.Parameters("#Assessment").Value = au_fname.Value
myCommand.Parameters.Add(New SqlParameter("#Plan", _
SqlDbType.Char, 8000))
myCommand.Parameters("#Plan").Value = phone.Value
myCommand.Parameters.Add(New SqlParameter("#HT", _
SqlDbType.VarChar, 40))
myCommand.Parameters("#HT").Value = address.Value
myCommand.Parameters.Add(New SqlParameter("#WT", _
SqlDbType.VarChar, 20))
myCommand.Parameters("#WT").Value = city.Value
myCommand.Parameters.Add(New SqlParameter("#BP", _
SqlDbType.Char, 10))
myCommand.Parameters("#BP").Value = state.Value
myCommand.Parameters.Add(New SqlParameter("#ServiceDate", _
SqlDbType.Char, 10))
myCommand.Parameters("#ServiceDate").Value = zip.Value
myCommand.Parameters.Add(New SqlParameter("#Diagnosis", _
SqlDbType.VarChar, 20))
myCommand.Parameters("#Diagnosis").Value = contract.Value
myCommand.Connection.Open()
' Test whether the new row can be added and display the
' appropriate message box to the user.
Try
myCommand.ExecuteNonQuery()
Message.InnerHtml = "<b>Record Added</b><br>"
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists with " _
& "the same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please " _
& "ensure the fields are correctly filled out"
Message.Style("color") = "red"
End If
End Try
myCommand.Connection.Close()
BindGrid()
End Sub
' BindGrid connects to the database and implements a SQL
' SELECT query to get all the data in the "Authors" table
' of the database.
Sub BindGrid()
Dim myConnection As SqlConnection
Dim myCommand As SqlDataAdapter
' Create a connection to the "EMR" SQL database located on
' the local computer.
myConnection = New SqlConnection("server=localhost;" _
& "database=EMR;Trusted_Connection=Yes")
' Connect to the SQL database using a SQL SELECT query to get all
' the data from the "Authors" table.
myCommand = New SqlDataAdapter("SELECT * FROM VisitData", _
myConnection)
' Create and fill a new DataSet.
Dim ds As DataSet = New DataSet()
myCommand.Fill(ds)
' Bind the DataGrid control to the DataSet. will remain hidden
MyDataGrid.DataSource = ds
MyDataGrid.DataBind()
End Sub
</script>
<body style="font: 10pt verdana">
<form id="Form1" runat="server">
<h3><font face="Verdana">Inserting Visit Data</font></h3>
<table width="95%">
<tr>
<td valign="top" nowrap="nowrap">
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
Visible="false"
EnableViewState="false"
/>
</td>
<body style="font: 10pt verdana">
<td valign="top">
<table style="font: 8pt verdana">
<tr>
<td colspan="2" bgcolor="#aaaadd" style="font:10pt verdana">
Add Visit Info:</td>
</tr>
<td>Subjective: </td>
<td>
<input type="text" id="au_id" value="" runat="server" maxlength="8000"
style="overflow: scroll; white-space: normal;" />
</td>
<tr>
<td nowrap>Objective: </td>
<td><input type="text" id="au_lname" value=""
runat="server"></td>
</tr>
<tr nowrap>
<td>Assessment: </td>
<td><input type="text" id="au_fname" value=""
runat="server"></td>
</tr>
<tr>
<td>Plan: </td>
<td><input type="text" id="phone" value=""
runat="server"></td>
</tr>
<tr>
<td>HT: </td>
<td><input type="text" id="address"
value="" runat="server"></td>
</tr>
<tr>
<td>WT: </td>
<td><input type="text" id="city" value=""
runat="server"></td>
</tr>
<tr>
<td>BP: </td>
<td>
<input type = "text" id="state" runat="server">
</td>
</tr>
<tr>
<td nowrap>Date of Service: </td>
<td><input type="text" id="zip" value=""
runat="server"></td>
</tr>
<tr>
<td>Diagnosis: </td>
<td>
<Input type="text" id="contract" value="" runat="server">
</td>
</tr>
<tr>
<td></td>
<td style="padding-top:15">
<input id="Submit1" type="submit" OnServerClick="AddAuthor_Click"
value="Add Visit" runat="server">
</td>
</tr>
<tr>
<td colspan="2" style="padding-top:15" align="center">
<span id="Message" EnableViewState="false"
style="font: arial 11pt;" runat="server"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
To change to a textarea, you need to keep the id="au_id" and runat="server" attributes
<input type="text" id="au_id" value="" runat="server" maxlength="8000" style="overflow: scroll; white-space: normal;" />
Becomes
<textarea runat="server" id="au_id" rows="4" cols="8">default text</textarea>
Note: Remove maxlength
To access the textarea value from your VB.NET code:
Reponse.Write(au_id.value)
Upon having this problem myself and spending some time trying to fix the problems with solutions from many many forum posts i managed to fix this same problem. Of all the forums I checked the problem was getting the string value from the textarea into an sql INSERT statement using the $_POST php superglobal variable
The only way I can see that actually works and doesnt throw up any errors is to ignore the column names when writing the INSERT statement.
So instead of:
"INSERT INTO tbl_dbTable ( Colummn1, Colummn2...) VALUES( '$_POST[textarea]', 'Value2'..)"
simply use:
"INSERT INTO tbl_dbTable VALUES( '$_POST[textarea]', 'Value2'..)"
The only downside is you MUST then list values for ALL the columns in the table, but it fixes the problem of getting the textarea value into an sql column.
hope this helps

Resources