Update a database record without refreshing a page. ASP VBscript - ajax

This requests for help follows a poorly worded request for help earlier (apologies).
I have two asp/vbscript pages. The second page (containing only <% vbscript %> is called when a form on the first page is submitted.
The code on the second page causes an update to a database record and is as follows (the fields are populated from querystring variables.):
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET " & fieldPrefix & "has_text1 = 'YES', " & fieldPrefix & "text = '" & fieldUpdate & "' WHERE id = " & tempid & ""
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
All the form submit does is to cause the database update to happen - nothing else.
The page then response.redirects back to the calling page. This causes a refresh and lot of data on the first page to be lost - this is what I'm trying to avoid.
Can someone please tell me how I can carry out the update without leaving and then refreshing the calling page please? I've been told Ajax can do this but I have no experience at all of using it.
Many thanks

First of all, change your code to use parameters so you will be protected against SQL Injection attack:
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET " & fieldPrefix & "has_text1 = 'YES', " & fieldPrefix & "text = ? WHERE id = ?"
Set MyCommand = Server.CreateObject("ADODB.Command")
Set MyCommand.ActiveConnection = MyConn
MyCommand.CommandType = 1
MyCommand.CommandText = SQLString
MyCommand.Parameters.Append(MyCommand.CreateParameter("#text", 200, 1, 0, fieldUpdate))
MyCommand.Parameters.Append(MyCommand.CreateParameter("#id", 3, 1, 0, tempid))
MyCommand.Execute()
MyConn.Close
Set MyCommand = Nothing
Set MyConn = Nothing
Having this, the next step is adding hidden frame in the first page:
<iframe id="MyFrame" name="MyFrame" style="display:none;"></iframe>
And finally simply add target to your <form> tag like this:
<form action="SecondPage.asp" target="MyFrame">
That's it... now the form will be submitted "inside" the hidden frame, will still trigger the database update and won't cause any refresh.

Related

Populate and sort a ComboBox from another ComboBox, VBA

Hi Everyone I am having trouble getting a ComboBox to sort, when another combobox is selected.
I think I have the Right SQL Syntax but I cant seem to get the vba to run it through; currently the vba returns all of the states in the recordset regardless of the company.
Private Sub CboCountry_Click()
Set db = CurrentDb
Dim SQLStr As String
Set RsState = db.OpenRecordset("T2States", dbOpenSnapshot, dbSeeChanges)
'populates combobox with recordset, that is defined by the country input from the form
RsState.MoveFirst
Do While Not RsState.EOF
Me.CboState.RowSource = Me.CboState.RowSource & RsState("StateID") & ";" & RsState("State") & ";"
RsState.MoveNext
Loop
I think this is the right SQL String but I'm having trouble to get it to work.
'SQLStr = "SELECT T2States.StateID, T2States.States, T2States.CountryID" & _
" FROM T2States GROUP BY T2States.StatesID" & _
" WHERE T2States.CountryID = """ & Me.CboCountry.Value & """"
Any help will be greatly appreciated.
Edit#1
See Full Code below, the error that pops up when I substitute SQLStr into the Openrecordset is a Run-time error '3078' the microsoft access database engine cannot find the input table or query 'SQLStr'. Make sure it exists and that its name is spelled correctly.
What should happen is when a country is selected from CboCountry combobox, it will load the CboState combobox by sorting the recordset by CountryID
see below for both code parts
Private Sub Form_Load()
Set db = CurrentDb
Set RsCompany = db.OpenRecordset("T1Company", dbOpenDynaset, dbSeeChanges)
Set RsCountry = db.OpenRecordset("T2Countries", dbOpenSnapshot, dbSeeChanges)
Set RsAddress = db.OpenRecordset("T1Addresses", dbOpenDynaset, dbSeeChanges)
Set RsAddressType = db.OpenRecordset("T2AddressType", dbOpenSnapshot, dbSeeChanges)
Set RsCompanyAddress = db.OpenRecordset("T3Company_Address", dbOpenDynaset, dbSeeChanges)
Me.CboCountry = Null
Me.TxtAddress1 = Null
Me.TxtAddress2 = Null
Me.TxtAddress3 = Null
Me.TxtCity = Null
Me.CboAddressType = Null
Me.CboCountry = Null
Me.CboState = Null
Me.TxtPostalCode = Null
Me.TxtCompanyID = Null
Me.TxtLegalName = Null
Me.TxtNickname = Null
Me.TxtAddressID = Null
RsCountry.MoveFirst
Do While Not RsCountry.EOF
Me.CboCountry.RowSource = Me.CboCountry.RowSource & RsCountry("CountryID") & ";" & RsCountry("Country") & ";"
RsCountry.MoveNext
Loop
RsAddressType.MoveFirst
Do While Not RsAddressType.EOF
Me.CboAddressType.RowSource = Me.CboAddressType.RowSource & RsAddressType("AddressTypeID") & ";" & RsAddressType("AddressType") & ";"
RsAddressType.MoveNext
Loop
Me.TxtLegalName.SetFocus
End Sub
Private Sub CboCountry_Click()
Set db = CurrentDb
Dim SQLStr As String
'SQLStr = "SELECT T2States.StateID, T2States.State, T2States.CountryID" & _
" FROM T2States" & _
" WHERE T2States.CountryID = """ & Me.CboCountry.Value & """"
Set RsState = db.OpenRecordset("T2States", dbOpenDynaset, dbSeeChanges)
'populates combobox with recordset, that is defined by the country input from the form
RsState.MoveFirst
Do While Not RsState.EOF
Me.CboState.RowSource = Me.CboState.RowSource & RsState("StateID") & ";" & RsState("State") & ";"
RsState.MoveNext
Loop
End Sub
Let us see
1- sure you've to append with
Having T2States.States, T2States.CountryID
2- Error exist in it, extra 's' in the Column name:
GROUP BY T2States.StatesID
3- put all the code and i'll check with you what you miss.
best regards
This one turned out to be a quick fix in the Property Sheet under the DATA tab, the Row Source Type had to be changed back to 'Table/Query' from a 'Value'.
There is VBA that could account for this but it was just a simple as changing that Row Source.
The Reason for the mix up, for a quick bit of background if it helps, is that all my combo boxes are unbound and I was binding them with VBA Recordsets so the rowsource has to be a value list - Essentially the VBA is writing the list everytime it loads.
Where as when I started using SQL to generate the recordset, even though it was in VBA I had to change the property back to Table/Query.
Thanks.

I have a trouble getting an element from HTML page

what I do is I navigate to a site then I want to find an element called "jobId"
Const PAGE_LOADED = 4
Set objIE = CreateObject("InternetExplorer.Application")
Call objIE.Navigate("http://172.25.25.32:8090/")
objIE.Visible = True
Do Until objIE.ReadyState = PAGE_LOADED : Call WScript.Sleep(100) : Loop
objIE.Document.all.Username.Value = "ashishgi"
objIE.Document.all.Password.Value = "apac2015#"
If Err.Number <> 0 Then
msgbox "Error: " & err.Description
End If
Call objIE.Document.all.gaia_loginform.submit
Set objIE = Nothing
when I use ViewSource this is the elements I want to use :
input type="submit" name="btnsubmit" value="Login" id="logincaption" class="button" style="color:#565656"
So, you're trying to click submit? Your explanation is difficult to interpret what you want the script to do. Based on the element you displayed on your sample is a submit button. It's been a while since I automated a form but I believe you want something to this effect.
objIE.Document.getElementsById("Username").Value = "ashishgi"
objIE.Document.getElementsById("Password").Value = "apac2015#"
' If you want to use the button by name
objIE.Document.all.item("btnsubmit").click
' If you want to use the button by ID
objIE.Document.getElementsById("logincaption").click
'if that fails, make it an object like this and action the click.
Set Submit = objIE.Document.getElementsById("logincaption")
submit.click

Valid response causes "Subcript out of range"

I've got a classic ASP application that contacts a database and receives a valid response but then crashes with
Error Number 9: Subscript out of range
after exiting the IF block the db call is made in. What's odd is that the same code is currently working in production. As far as I can tell they're configured identically (but I suspect there's a subtle difference that's causing this issue) and have identical code bases.
What I want to know is:
Where is this array that I'm supposedly attempting to reach a non-existent index of? I don't see it and the error gives no line number. Is there a chance something is not working correctly in the adodb library?
Perhaps this is a common problem having to do with a certain patch and my particular db connection library? Have you had a similar experience?
How do I troubleshoot a problem that doesn't immediately present itself? Should I just start putting troubleshooting statements in the library?
Explanation of what's happening in the code: When the cookie "click" is received err.number is 0. When the cookie "bang" is received the err.number is 9. It then crashes with that error at the end of the IF block.
<%#Language="VBSCRIPT"%>
<% Server.ScriptTimeout = 150 %>
<%
On Error resume Next
%>
<!--#include file="adovbs.inc"-->
<!--#INCLUDE FILE="DBConn.asp"-->
<!--#INCLUDE FILE="ErrorHandler.asp"-->
<%
'Application Timeout Warning
sessionTimeout = 20
advanceWarning = 5
jsTimeout = (sessionTimeout - advanceWarning) * 60000
'If the users session has expired
If Session("USERNAME") = "" or Session("USERNAME") = NULL Then
Response.Redirect("default.asp")
End If
'If the user has just changed their password. Prompt them that it was successfully changed
If Request("changePasswd") = "true" Then
Response.Write("<script language='Javascript'>alert('Your Password Has been Successfully Changed!');</script>")
End If
Dim connection, cmd, objRS, latestDate, lastDateJPMC, firstDateJPMC, lastDateWACH, firstDateWACH, lastDateWFB, firstDateWFB, accountCount
Function calConvertDate(theDate)
Dim yr, mn, dy, dtSplit
dtSplit = Split(theDate,"/")
yr = dtSplit(2)
mn = dtSplit(0)
dy = dtSplit(1)
if Len(mn) = 1 then mn = "0" & mn
if Len(dy) = 1 then dy = "0" & dy
calConvertDate = "[" & yr & "," & mn & "]"
End Function
set connection = Server.CreateObject("adodb.connection")
connection.Open DBConn
connection.CommandTimeout = 60
set connection = Server.CreateObject("adodb.connection")
connection.Open DBConn
connection.CommandTimeout = 60
'Get Earliest & Latest Date in Database
If Err.Number = 0 Then
Response.Cookies("CLICK")=Err.number
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
Set .ActiveConnection = connection
.CommandText = "CIRS_Admin.spGetLatestDate"
.CommandType = adCmdStoredProc
set objRS = .Execute
End With
latestDate = calConvertDate(objRS("latestDate"))
Response.Cookies("latestdate")=objRS("latestDate")
objRS.Close
Set objRS = Nothing
Response.Cookies("BANG")=Err.number
End If
To debug, please add a statement like
Response.Write (objRS("latestDate"))
before the line
latestDate = calConvertDate(objRS("latestDate"))
so you can see if (for example) the date returned from the server has "-" as separator instead of "/" or if an empty value is returned.
After understanding what is causing the problem you can solve it
1.Where is this array that I'm supposedly attempting to reach a non-existent index of? I don't see it and the error gives no line number. Is there a chance something is not working correctly in the adodb library?
This is your array:
yr = dtSplit(2)
mn = dtSplit(0)
dy = dtSplit(1)
What's odd is that the same code is currently working in production. As far as I can tell they're configured identically (but I suspect there's a subtle difference that's causing this issue) and have identical code bases.
May be you have different regional settings?
I strongly suggest to you use better error handling.
Internal Server Error 500 w/ IIS Log

Reduced performance when creating object in classic asp

Trying to measure a website performance I created a simple logging sub to see what parts are slow during the execution of a classic asp page.
sub log(logText)
dim fs, f
set fs = Server.CreateObject("Scripting.FileSystemObject")
set f = fs.OpenTextFile("log.txt", 8, true)
f.WriteLine(now() & " - " & logText)
f.Close
set f = Nothing
set fs = Nothing
end sub
log "Loading client countries"
set myR = Server.CreateObject("ADODB.RecordSet")
myR.ActiveConnection = aConnection
myR.CursorLocation=2
myR.CursorType=3
myR.LockType=2
myR.Source = "SELECT * FROM CC ORDER BY ccName ASC"
log "Opening db connection"
myR.open()
log "Opened db connection"
Here are the results (only showing the time part):
...
11:13:01 - Loading client countries
11:13:06 - Opening db connection
11:13:06 - Opened db connection
...
Creating the ADODBRecordSet and setting a few properties takes about 5 seconds. This does not always happen, sometimes the code is executed fast, but usually when I reload the page
after a few minutes the loading times are more or less the same as the example's. Could this really be a server/resources issue or should I consider rewriting the code? (My best option would be to write this in C#, but I have to study this code first before moving forward anyway).
Update: I added more code after receiving 1st comment to present a few more code. Explanation: The code creates a combobox (selection menu) with the retrieved countries (it continues where the previous piece of code stopped).
if not myR.eof then
clientCountries = myR.getrows
send("<option value='0'>Select country</option>")
log "Creating combobox options"
for i = 0 to ubound(clientCountries, 2)
if cstr(session("clientCountry")) <> "" then
if cstr(clientCountries(1, i)) = cstr(session("clientCountry")) then
isSelected = "selected" else isSelected = ""
end if
end if
if cstr(session("clientCountry")) = "" then
if cstr(clientCountries(1, i)) = "23" then
isSelected = "selected"
else
isSelected = ""
end if
end if
optionString = ""
optionString = clientCountries(2, i)
send("<option value='" & clientCountries(1, i) & "' " & isSelected & ">" & convertToProperCase(optionString) & "</option>")
next
log "Created combobox options"
end if
myR.Close
myR.ActiveConnection.close
myR.ActiveConnection = nothing
set myR = nothing
log "Loaded client countries"
The next two log entries are as follows:
11:13:06 - Creating combobox options
11:13:06 - Created combobox options
...
So far, the SELECT query as the rest of the page (2 or 3 queries more) is executed within the next second more or less. The only part slowing the page down is what you can see in the first part of the log. I'm not sure if I can profile the SQLServer, because I only have cPanel access. This is the only way I know of, unless there's something else I could have a look at.
First, Check your connection string, I've experienced slower times with certain providers. The best provider I've found for classic asp is sqloledb
Second, I would close my SQL object before I did the For statement on the GetRows() array. You don't want to keep that open if you don't need to.
Third, I'd use stored procedures. You'll get a performance improvement by saving on compile time.
Fourth, I would avoid doing a SELECT * statement at all cost, instead I would return ONLY the columns I need. (Your code looks like it only needs 2 columns)
Fifth, I would build indexes on the tables taking longer than expected.
If this doesn't resolve the issue, I would consider other languages/solutions. Not sure what the dataset looks like, so can't say if a flat-file database should be considered or not.
Also, try this for a recordset instead and see what happens:
Set myR = Server.CreateObject("Adodb.Recordset")
myR.Open "SELECT * FROM CC ORDER BY ccName ASC", aConnection
If myR.RecordCount > 0 Then clientCountries = myR.GetRows()
myR.Close
Set myR = Nothing
If IsArray(myR) Then
For ....

get value of Checkbox in datagrid

I am working with windows application.
I have a datagrid in vb.net. Its first column is a checkbox. I want to know which checkboxes are checked and which are not.
My code is :
Dim dr As DataGridViewRow
For i = 0 To gdStudInfo.RowCount - 1
dr = gdStudInfo.Rows(i)
att = dr.Cells(0).Value.ToString()
If att.Equals("Present") Then
qry = "insert into Stu_Att_Detail values(" & id & "," & gdStudInfo.Rows(i).Cells(1).Value.ToString() & ",'" & dr.Cells(0).Value.ToString() & "')"
con.MyQuery(qry)
End If
Next
I am getting correct values for all checked check box, but it gets error when the checkbox is not checked.
What if you try this?
If Not String.IsNullOrEmpty(dr.Cells(0).Value) Then
'do stuff here
End If

Resources