Javascript posting to VB.Net page multiple times - javascript

Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!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 runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.

I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)

I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.

Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.

Related

Create javascript Alert before response.end() vb.net

I have a button to generate rar file then download it , i want to create an alert javascript if download success or file is exist in directory.. My code :
Using zip As New ZipFile
Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Download/" & "/" & NameFolder))
Dim files As New List(Of ListItem)()
zip.AlternateEncodingUsage = ZipOption.AsNecessary
zip.AddDirectoryByName("MyRarFileName")
For Each filePath As String In filePaths
files.Add(New ListItem(Path.GetFileName(filePath), filePath))
zip.AddFile(filePath, "MyRarFileName")
Next
Response.Clear()
Response.BufferOutput = False
Dim zipName As String = [String].Format("MyRarFileName_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
Response.ContentType = "application/zip"
Response.AddHeader("content-disposition", "attachment; filename=" + zipName)
zip.Save(Response.OutputStream)
Dim ls_Dir As New IO.DirectoryInfo(Server.MapPath("~/Download" & "/" & NameFolder))
Dim ls_GetFile As IO.FileInfo() = ls_Dir.GetFiles()
Dim ls_File As IO.FileInfo
For Each ls_File In ls_GetFile
File.Delete(ls_File.FullName)
Next
ls_Dir.Delete(True)
Response.End()
End Using
I want to call an alert javascript like below :
If DataExist > 0 Then
'My Alert
Using zip As New ZipFile
'Code for generate and download rar
End Using
End If
I have tried :
Dim myScript As String = "window.alert('Download Success !');"
ClientScript.RegisterStartupScript(Me.GetType(), "myScript", myScript, True)
and call javascript function :
<script>
function MyMessage(){
alert('Download Success');
}
</scipt>
ClientScript.RegisterStartupScript(Me.GetType(), "MyMessage", MyMessage(), True)
But alert still doesn't appears, any suggest ?
Thanks you

Where find URL in return of an ASHX returning RedirectFromLoginPage

I have an ashx receiving login/password and send error message if it's wrong but if it's good make a RedirectFromLoginPage.
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
FormsAuthentication.SignOut()
Dim LesDatas As New MyEntities
Dim username As String = GetParamURL("UserName")
Dim password As String = GetParamURL("Password")
If Not IdentifyCollab(username, password, LesDatas) Then
FormsAuthentication.SignOut()
context.Session.Abandon()
HelperJournal.Log("Echec de connexion :" & username)
loginStatut = LoginFailed(GetIPAddress, LesDatas)
context.Response.ContentType = "text/plain"
context.Response.Write(loginStatut.Msg)
Else
FormsAuthentication.RedirectFromLoginPage(ConnectedUser.Login, False)
End If
End Sub
If You use directly the ashx in browser url zone : http://localhost:5959/login/login.ashx?UserName=toto&Password=MyPass, you're directly redirect in the default page http://localhost:5959//choix.aspx
But If I call it from JS :
$.post("/Login/Login.ashx?UserName=" + mdp1 + "&Password=" + mdp2, {},
function (response,tt,ti) {
if (response.indexOf("html") === -1) $("#ResultConnexion").html(response); else {
window.history.pushState("", "", '/choix.aspx');
var newWindow = window.open("", "_self");
newWindow.document.write(response);
}
});
I need to use pushState to correct the url in browser, and window.open/write to display the defaultpage. But like you can see, I write in hard "/choix.aspx", cause the url are not modify and stay on referer URL (my login page http://localhost:5959/Login/login.html)
But If I can have automaticly the good URL when I use in browser my ashx, it's seems the URL information is sent.
In function use in response of $post I note severals parameters : response,tt,ti
response is the text to display page in return
tt="success"
ti is an object with lot of informations... but I don't see where is URL.
If someone can help me.
I just find a way here
In my masterpage
Private Sub Choix_Init(sender As Object, e As EventArgs) Handles Me.Init
Response.AppendHeader("X-MONAPPLI", HttpContext.Current.Request.Url.PathAndQuery)
End Sub
and in login.js
$.post("/Login/Login.ashx?UserName=" + mdp1 + "&Password=" + mdp2, {},
function (response, tt, xhrreq) {
if (response.indexOf("html") === -1) $("#ResultConnexion").html(response); else {
window.history.replaceState("", "", xhrreq.getResponseHeader("X-MONAPPLI"));
var newWindow = window.open("", "_self");
newWindow.document.write(response);
}
});
I use replaceState instead of pushstate cause I've secyrity error

Lost on AJAX to .ASP file

I have a need to automate data collection for users who visit specific pages of my site. To do this, I'm querying the LDAP. The LDAP query works just fine when I double click on the file locally (.vbs). However, when I double click on it while it's on the server, it doesn't work (as would be expected). However, I'm as new as new can get to writing VBScript.
After reading a few articles I modified the code and changed the extension to .asp. I ended up with this:
<%
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
Return employee
%>
In the JavaScript function which would call this .asp file via ajax, I am able to get the employee number which I think could be received by the .asp file and do the rest of the query.... However, I'm not even sure if I'm returning everything correctly in the VBScript. Furthermore, I'm not even sure if I should be using a GET or POST AJAX call. Can someone point me in the right direction?
Updated 03/22/2017 at 10AM CDT
I've finally gotten back to the office and tried to play around. I'm still a little lost. I've made some updates to the code below you'll see the javascript and the VBScript
FIRST the JavaScript:
var employee = {};
function getEmp() {
var ldapUserName = ADSystem.UserName;
$.ajax({
type: "POST",
data: ldapUserName,
url: "https://here.is.my/url.asp",
success: $.ajax({
type: "GET",
dataType: "json",
success: function(responseText) {
employee = responseText;
},
error: function() {
alert("No Data Received");
}
}),
error: function() {
alert("Connection Failed");
}
});
}
Now here is the updated VBScript based on a few things I read and the suggestions from here:
<%
Public Function empDemo(username)
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.username
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
response.write "{ site: " & employee(0) & ","
& "empNum: " & employee(1) & ","
& "empFName: " & employee(2) & ","
& "empLName: " & employee(3) & ","
& "empFullName: " & employee(4) & ","
& "empExt: " & employee(5) & ","
& "empTitle: " & employee(6) & "}"
End Function
%>
Currently, I'm getting the alert stating "No Data Received". What am I doing wrong?
Instead of "return Employee", have you tried:
response.write employee
or maybe
response.write employee.sAMAccountName
Is this VB6? Not sure what libraries are available in classic asp, so you might have to manually write the data in JSON form... i.e...
response.write "{ name: " & employee.sAMAccountName & "}"

ASP.net loading just data onload instead of page HTML

I am having some issues with just wanting to output some data to the page without having all the HTML load. I am using AJAX to call the same ASPX page in order to populate some data to be returned to the AJAX call. However, it currently does call and it does populate with the correct data BUT it does not seem to want to place that data onto the page.
It currently has an error loading the page of "This webpage is not available: ERR_CONNECTION_RESET"
When I load the page like so:
http://localhost:2765/Default.aspx?Data=viewData
is where I receive the error of "This webpage is not available: ERR_CONNECTION_RESET". Placing some code breaks in, I can confirm that it does populated the needed data but never seems to display it on the page and it also seems to call the page at least 2 times before finally stopping (possibly causing the error above).
The default.aspx code is this:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="AdminPanel._default" %>
<% If loadHTMLPage Then %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
....[more HTML code here]....
<script type="text/javascript">
$(document).ready(function () {
var clickedButtonName = "";
$('#dashboardData, #viewData, #updateData, #addData, #deleteData').click(function() {
clickedButtonName = '#' + $(this).attr("id");
$.ajax({
url: $(this).attr("id") + ".aspx",
dataType: 'html',
timeout: 10000,
success: function (html) {
$("#jQueryLoadHere").html(html);
$('#dashName').html("<strong>" + $(clickedButtonName).data("title") + "</strong> Page");
$('#dashboardData_LI, #viewData_LI, #updateData_LI, #addData_LI, #deleteData_LI').attr('class', 'nav-parent');
$(clickedButtonName + '_LI').attr('class', 'nav-parent nav-active active');
}
});
});
});
</script>
</form>
</body>
</html>
<% Else %>
<% =pageData %>
<% End If %>
The codebehind is this:
Public Class _default
Inherits System.Web.UI.Page
Dim whatData As String = Nothing
Public loadHTMLPage As Boolean = True
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
whatData = Request.QueryString("Data")
Response.Write(whatData)
If whatData = "viewData" And hasLoaded = False Then
loadHTMLPage = False
hasLoaded = True
Call workingGetFEBList()
End If
End Sub
Private Sub workingGetFEBList()
Dim request As WebRequest = WebRequest.Create(apiURL & appID & "/" & formID & "?format=text/xml")
request.Method = "GET"
request.Credentials = CredentialCache.DefaultCredentials
Dim response1 As WebResponse = request.GetResponse()
Dim dataStream As Stream = response1.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim serverResponse As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
Response.Close()
Dim theOutput As String = parseXML2JSON(serverResponse)
pageData = theOutput
End Sub
If I comment out:
Call workingGetFEBList()
pageData = theOutput
and refresh the page - it works just fine loading the page (blank white page with just viewData text on it).
Likewise, just loading the page:
http://localhost:2765/Default.aspx
Loads up the page with the normal HTML just fine.
So what could I be missing??

Change page from an Iframe to the Main Window

I'm working inside an iframe and when i finish my job I want to change page (NOT inside iframe) but out side of this iframe, in the main window.
For this I use the following Sub:
Public Sub ChangePage(sender As Object, e As EventArgs)
Dim myNewAsp As New AspNetSqlProvider
Dim dbHandler As New DBHandler
Dim srvHandler As New ServerHandler
Dim aspProvider As New MyAspNetSqlMembershipProvider
Dim errAnswer As New Register
Dim assit As New Assistance
Dim currentUser As MembershipUser = Nothing
Dim message As String = Nothing
Dim msg As String = Nothing
Try
Dim url As String = "/Pages/Account/Login.aspx"
Dim postWindow As Object ' "/Pages/Account/Assistance.aspx"
Dim startWindow As Object ' "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim myServerName As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
url = myServerName + url
startWindow = Me.GetType().FullName
postWindow = Assistance.PageUrlType
msg = "Hellow World"
'msg = "<script type='text/javascript'> $(document).ready(function(){ window.location.href='" + url + "'; }); </script>"
Dim script As Type = Me.Page.GetType() ' Assistance.PageType.BaseType
Dim postmsg As String = "ChangePage('" & startWindow & "', '" & postWindow & "', '" & msg & "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "sendMessage") Then
Page.ClientScript.RegisterStartupScript(script, "sendMessage", postmsg)
End If
Catch eq As SqlException
srvHandler.ErrorAnswer = DBHandler.GetError(1, Nothing, Nothing, eq, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword "
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
Catch Ex As Exception
srvHandler.ErrorAnswer = DBHandler.GetError(3, Ex, Nothing, Nothing, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword"
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
End Try
End Sub
I use the following script in the Page inside the iFrame:
<script type="text/javascript">
function ChangePage(startPage, sendPage, message) {
var sPage = document.getElementById(startPage);
sPage.contentWindow.postMessage(message, sendPage);
}
</script>
I also use the following script in the Page I want to change (parent Page):
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
event.origin !== message;
event.source.postMessage("'" + message + "'", event.origin);
return;
}
what I got from the above is to have the desired page (the message in the example) BUT inside of the frame.
The scrip in the Help01.aspx page is executed just fine. But in this window, and not in the parent one (Assistance,aspx)
As a result I can't get out of the iFrame (which is inside of a table).
Is someone to know what to do about it?
I think you'll need to use something like postMessage here. It depends on the browsers you need to support, but support is pretty good. That will let you "talk" between the main window and the iFrame.
That link will walk you through how to set it up, but the gist of it is that you'll need to attach an event listener to the main window and then post a message from the iFrame to the outer window. Then do your redirect in the outer window when the message comes in.
So where you have Dim msg As String... you'll want that to be some code that posts a message to the outer frame. Something like window.postMessage(..)

Categories

Resources