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

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

Related

View the file from base64 string instead of varbinary

This is my simple program on downloading file from a varbinary string on click.
Controller:
public ActionResult Download(string StudentID, string SQNC)
{
string query = "exec spToGetVarbinaryString'" + StudentID + "','" + SQNC + "' ";
string dataStr = GlobalFunction.DataTableToJSON(GlobalFunction.TableFromMSSQL(dbname, query));
dynamic data = JsonConvert.DeserializeObject(dataStr);
byte[] file = data[0].ImgVarbinary;
return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, (string)data[0].FileName);
}
how I download the File:
<a type="button" href="ControllerName/Download?StudentID=${row.StudentID}&SQNC=${row.SQNC}" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">View File</a>
Now, I want the file instead of being downloaded on click, It will appear on tab or new. I tried the method of converting my Varbinary to Base64 string, but it doesnt read the PDF file for this example below.
From VarBinary to Base64 in SQL
update a set a.ImgStr=baze64
from #mytemptable
cross apply (select ImgVarbinary as '*' for xml path('')) T (baze64)
where a.ImgVarbinary is not null
Displaying Base64 PDF File (Display doesn't work)
<iframe width="500" height="500"
src="data:application/pdf;base64,<base64stringhere>"
I found a sample base64 data in this JSFiddle link, I tried it on local and it works.
Image example (left one: my base64 string. Right one: base64 from the js fiddle)
How can I do this and why my base64 string isn't working well? Thanks for answering.
add something like this on click event to read bytes....
public class LoadPdfFileHandler : IHttpHandler
{
public bool IsResuable => false;
public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["id"];
// TODO: Verify that the user is allowed to view the specified record.
using (var connection = new MySqlConnection("..."))
using (var command = new MySqlCommand("SELECT Data, ContentType FROM SomeTable WHERE ID = #ID", connection))
{
command.Parameters.AddWithValue("#ID", id);
connection.Open();
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
if (!reader.Read())
{
context.Response.StatusCode = 404;
return;
}
string contentType = (string)dr["ContentType"];
if (string.IsNullOrEmpty(contentType)) contentType = "application/octet-stream";
context.Response.ContentType = contentType;
byte[] bytes = (byte[])dr["Data"];
context.Response.BinaryWrite(bytes);
}
}
}
}
Then Write Frame Using this...
myiframe.Attributes["src"] = ResolveUrl("~/loadPdfFile.ashx?id=" + idOfTheRecordToLoad);
You can check Other Reference here image reference

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

Servlet-Response containing text (for display) as well as file download

I'm trying to download a file from my server through a Java Servlet.
The Problem I have is that when I enter the servlet url directly (https://localhost:8443/SSP/settings?type=db_backup) I get the servlet to execute its code and prompt me with a download dialog.
But I would like to call the servlets doGet method via Javascript to wrap it with a progress bar of some kind.
Problem here: Code in servlet is executed but I dont get the download prompt for the file.
My Code so far:
HTML:
<!-- Solution #1 -->
<button class="btn_do_db_backup" type="button">DB-Backup #1</button>
<!-- Solution #2 -->
<form action="/SSP/settings?type=db_backup" method="GET">
<button type="submit">DB-Backup #2</button></br>
</form>
JS:
// Solution #1
$(".btn_do_db_backup").click(function(e){
e.preventDefault();
$.get("settings?type=db_backup", function(data){
if(data != ""){
//further coding
}
});
// Having the code below works but doesnt
// give me the chance to wrap the call with a loading animation
//document.location = "/SSP/settings?type=db_backup";
});
Servlet:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// PART 1
// execute srcipt to generate file to download later on
StringBuffer output = new StringBuffer();
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "D:\\TEMP\\sql_dump.cmd");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String filename = "";
int tmp = 0;
while (true) {
line = r.readLine();
if (line == null) { break; }
output.append(line + "\n");
// code for finding filename not optimal but works for now -> redo later on
if(tmp == 1){
filename = line.substring(line.indexOf("db_backup_"), line.indexOf('"', line.indexOf("db_backup_")) );
}
tmp++;
}
// PART 2
// download the file generated above
OutputStream out = response.getOutputStream();
String filepath = "D:\\TEMP\\sql_dump\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
out.close();
fileInputStream.close();
}
Solution #2 works great, I get a popup to download the file.
Solution #1 calls the servlets doGet-method (via the above JS-Code and the code from my servlet is executed correctly) but I dont get a download popup
I would like to go with solution #1 though as this gives me the opportunity to wrap the $.post call with a loading animation.
What am I missing within solution #1 to get that download popup to shop up?
EDIT 1:
I found that data in the $.get() function is filled with the content of the desired file. I can now display the content of a .txt file in a div for example but I would like to donwload said .txt file instead.
EDIT 2:
Solved it, see my answer below for details & comment/ansewer if you think it can be done in a better way
after quite some time trying to get it to work I found a solution that works. There may be better ones but thats the one I came up with.
Hope this may be helpfull for others as well.
Basic explanation of what I did here:
Have a form do a GET-Request (via JS) to a java servlet
The servlet executes a commandline script (in my case a sql-dump of my postgreSQL DB)
The servlets gathers the output from the commandline and the contents of the generated file (the sql_dump) and puts them in the response
The client gets the response and cuts it into 3 pieces (commandline output, filename & contents of sql_dump-file)
Then (via JS) the commandline output is shown in a textarea for a better overview of what the script actually did
The contents of the sql_dump-file is processed by JS-Code to generate a file to download (eihter manually via a button or automatically)
So without further ado, here we go with the flow ... code :)
SOLUTION:
HTML:
<form id="form_download_db_backup">
<input type="submit" value="Create & Download DB-Backup"></br>
<a download="" id="downloadlink" style="display: none">download</a>
</form>
<div class="db_backup_result" id="db_backup_result" style="display: none;">
</br>Commandline-Output</br>
<textarea id ="txta_db_backup_result" rows="4" cols="50"></textarea>
</div>
JS:
$("#form_download_db_backup").submit(function(e){
e.preventDefault();
var spinner = new Spinner().spin();
var target = document.getElementById('content');
target.appendChild(spinner.el);
$.ajax({
url:'settings?type=db_backup',
type:'get',
success:function(data){
spinner.stop();
if(data != ""){
var str_data = "" + data;
// Cut commanline output from data
var commandline_output = str_data.substring( 0, str_data.indexOf("--End") );
//show commanline output in textarea
$("#txta_db_backup_result").html(commandline_output);
// Cut content of db_backup file from data
var sql_dump_content = str_data.substring( str_data.indexOf("--sql_d_s--") + 13,str_data.indexOf("--sql_d_e--") );//|
// Cut filename from data
var filename = str_data.substring( str_data.indexOf("--sql_d_fns--") + 15,str_data.indexOf("--sql_d_fne--") - 2 );
//-------------------------------------------------------------
// Prepare download of backupfile
var link = document.getElementById('downloadlink');
var textFile = null;
var blob_data = new Blob([sql_dump_content], {type: 'text/plain'});
// FOR IE10+ Compatibility
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob_data, filename);
}
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(blob_data);
link.href = textFile;
link.download = filename;
//link.style.display = 'block'; // Use this to make download link visible for manual download
link.click(); // Use this to start download automalically
//-------------------------------------------------------------
// show div containing commandline output & (optional) downloadlink
document.getElementById("db_backup_result").style.display = 'block';
}
}
});
});
Java-Servlet:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String type = request.getParameter("type");
if(null != type)switch (type) {
case "db_backup":
ServletOutputStream out = response.getOutputStream();
// Prepare multipart response
response.setContentType("multipart/x-mixed-replace;boundary=End");
// Start: First part of response ////////////////////////////////////////////////////////////////////////
// execute commandline script to backup the database
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "D:\\TEMP\\sql_dump.cmd");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String filename = "";
int tmp = 0;
while (true) {
line = r.readLine();
if (line == null) { break; }
// code for finding filename not optimal but works for now -> redo later on
if(tmp == 1){
filename = line.substring(line.indexOf("db_backup_"), line.indexOf('"', line.indexOf("db_backup_")) );
}
else{
line = line.replace("\u201E", "\'"); // replaces the lowercase " (DOUBLE LOW-9 QUOTATION MARK)
line = line.replace("\u201C", "\'"); // replaces the uppercase " (LEFT DOUBLE QUOTATION MARK)
}
out.println(line);
tmp++;
}
// End: First part of response ////////////////////////////////////////////////////////////////////////
// Separator of firt & second part
out.println("--End");
out.flush();
// Add filename in response (name of download file)
out.println("--sql_d_fns--"); // separator for filename (used to extract filename from response data)
out.println(filename);
out.println("--sql_d_fne--"); // separator for filename (used to extract filename from response data)
// Start: Second part of response ////////////////////////////////////////////////////////////////////////
out.println("--sql_d_s--"); // separator for content of db-dump (this is the text thats going to be downloaded later on)
String filepath = "D:\\TEMP\\sql_dump\\";
FileInputStream fileInputStream = new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
out.println("--sql_d_e--"); // separator for content of db-dump (this is the text thats going to be downloaded later on)
// End: Second part of response ////////////////////////////////////////////////////////////////////////
// End the multipart response
out.println("--End--");
out.flush();
break;
default:
break;
}
}
postgreSQL dump contain "lowercase" & "uppercase" quotation marks which I had to replace. I put a link to each here in case someone struggles with them as well. They have multiple encodings for those characters listed there.
Unicode Character 'DOUBLE LOW-9 QUOTATION MARK' (U+201E)
Unicode Character 'LEFT DOUBLE QUOTATION MARK' (U+201C)

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(..)

Javascript posting to VB.Net page multiple times

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.

Categories

Resources