i am unable to run ajax example - asp.net

Hello all i have the following code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest()
}
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readystate == 4 && xmlhttp.status == 200)
{
document.getElementById('hint').innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","sample.aspx?q=" + str ,true)
xmlhttp.send()
}
</script>
</head>
<body>
Type here: <input type="text" id="txt" onKeyUp = "showHint(this.value)"/>
Suggestion here: <div id="hint"></div>
</body>
</html>
but this example not working..it is saying access is denied (script error)
How to solve this..!
My aspx page follows like this
<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>

You have two separate issues. First, your sample.aspx should be sample.asp, as it is a classic asp page, not a .Net asp page. Make sure you change the path in the xmlhttp.open method as well.
Second, xmlhttp.readystate should be xmlhttp.readyState - note the capital S. Took me a bit to figure that part out.

The problem might be that you're running the HTML file in file:// protocol. As far as I'm aware, server files like .php & .asp don't work in file:// protocol.
If you really want this to work, try setting up Apache and put your files inside your server folder. If you're in Linux, it's in /var/www, with other operating systems I'm not so sure.
Also, thought it's unrelated, I would recommend changing your Doctype to <!DOCTYPE html> as it is the standard now. Sorry. You don't have to.
Best of luck!

Related

Response.write to <head>

Hopefully this won't be a difficult question for someone to answer, but I am having a lot of trouble finding the solution online. I am trying to add some HTML to my asp.net page from the code behind (It's VB.net). I would like to add the HTML into the head section of my page but can only add to the body currently.
You can put code in the head, just like the body. For example:
<%= CallAMethodThatReturnsAStringOfHtml() %>
You could try creating a property in your code behind and add your html in the Page_Load method:
Public MyHtml As String
then in the head section of your HTML just use the literal notation:
<%= MyHtml %>
Have runat attribute on your head element and you will be able to access it
<head id="someHead" runat="server">
</head>
Now in your codebehind, you can set it like
someHead.InnerHtml="<script src='somelibrary.js' ></script>";
I made this way, and it worked:
on the .aspx file:
...
<%
Response.Write(GetDisclosureText());
%>
...
on the aspx.cs file:
protected string GetDisclosureText()
{
string disclosure = "";
// ...Apply custom logic ...
if (!string.IsNullOrEmpty(disclosure))
{
return disclosure;
}
return "Error getting Disclosure Text";
}
Note the only difference is that I call Response.Write, not just the function.

Current Universal time in classic asp

How can I get the current time as Universal time in classic asp. I know how to get in C# and I am getting the universal time in c# with following line ((DateTime.Now).ToUniversalTime()).ToString("s") and this code gives me time like this 2012-07-09T10:29:49
But I want to know the equivalent in classic asp. Thanks
As Ian pointed out you can generate a UTC time via Javascript.
You specified "ASP Classic" which of course includes Javascript as a language (Actually JScript, based on ECMAScript v3), so there's one answer for you: Call (new Date()).toUTCString().
If by chance you prefer to code your pages in mostly VBScript, you can mix in just a little JScript to get it done. You don't need to resort to Server.Execute or Sessions to make that happen.
This works for me:
<%# language="VBScript" %>
<script language='JScript' runat='server'>
function jsGetUTCTime() {
var d = new Date();
return d.toUTCString();
}
</script>
<script language='VBScript' runat='server'>
Function getUTCTime()
' Use JScript to get the current GMT time stamp
getUTCTime = jsGetUTCTime()
End Function
</script>
<!DOCTYPE html>
<html>
<head>
<title>Mix</title>
</head>
<body>
<h2>The time is:</h2>
<%= getUTCTime() %>
</body>
</html>
According to u229.no, there isn't any built-in way in VBScript to convert to UTC.
Take a look at the code the author provided below which uses JScript, and how you can call this from VBScript.
The GetServerGMT routine will return something like: Wed, 01 Feb 2006 15:21:59 UTC.
Function GetServerGMT()
// Use JScript to get the current GMT time stamp and store it in Session("ServerGMT")
Server.Execute "GetServerGMT.asp"
GetServerGMT = Session("ServerGMT")
End Function
And this is how the GetServerGMT.asp file with the jscript code looks like:
<%#language="jscript"%>
<%
var od = new Date();
var nd = od.toUTCString();
Session("ServerGMT") = nd;
%>
There are other jscript methods that you can use as well.
An alternative approach is
%>
<script runat="server" language="javascript">
function getTimezoneOffset() {
return (new Date()).getTimezoneOffset()
}
</script>
<%
Function nowUtc()
nowUtc=DateAdd("n",getTimezoneOffset(),Now)
End Function
Variation on above code
<%# language="VBScript" %>
<!DOCTYPE html>
<html>
<head>
<script language='Javascript' runat='server'>
// good for creating cookie timestamps that match RFC 1123
function jsGetFutureTimeGMT(minutes) {
var d = new Date();
var future = new Date();
future.setTime(d.getTime() + (minutes*60000));
var utcString = future.toUTCString();
var tz = utcString.indexOf("UTC");
if (tz > 0) {
utcString = utcString.substring(0, tz) + "GMT";
}
return utcString;
}
</script>
<title>ASP Classic RFC 1123 compliant GMT timestamp</title>
</head>
<body>
<h2>ASP Classic RFC 1123 compliant GMT timestamp</h2>
<pre>
The VBS time right now is: <%= Now() %>
The time in 10 minutes is: <%= jsGetFutureTimeGMT(10) %>
</pre>
</body>
</html>
If your application is connected to a database, you can probably get a timestamp from the database with a simple fast query. For example, in MySQL it's: SELECT unix_timestamp().
This will give you a Unix Timestamp (seconds since the Unix Epoch). From there convert into whatever format you like.

Multiple fileuploads with ASP.NET MVC

Hi,
I have implemented this plugin by Steve Sanders from 2008. In my solution I have 3 buttons for 3 uploads and this works just fine. But ist not a perfect fit and the question is if thera is a better solution for me?
What I need is :
Be able to upload multiple files
When the Control Action is triggered It should be possible to work with the files
The enduser should be able to cancel a uploaded file(this is not possible with Steves plugin as far as I know)
Easy to use with ASP.NET MVC
If a post is done to the Control Action and a validation error is thrown back the uploads may not disappear.
Pleas Advice
How about using Uploadify? I have used it before, and it works great. But do notice that it also needs a Flash front-end in order to work...
Take a look at this StackOverflow question - there you'll find more info of how to use it with ASP.NET MVC.
Under the hood the Steve Sanders' plugin uses swfUpload which can support everything you need. His plugin however does not seem to expose all of the features of swfUpload such as canceling uploads.
I use swfUpload to it's full extent on my sites supporting multiple files, canceling uploads, validation without canceling other uploads, etc.
Here's a demo of swfUpload in action where you can cancel uploads
Another option is SlickUpload.
It's not free but definitely worth it in my opinion. I used it in an MVC project recently and was extremely happy with it. Best upload plugin I've ever used + it comes with all sorts of validation helpers.
It's fully customizable too.
Download the trial and have a look for yourself :)
It's not possible with pure ASP.NET.
You need to take JQuery uploadify.
It's the best you can find, trust me, I tried for an entire day.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MassUpload.aspx.vb" Inherits="Raumplaner_New.MassUpload" %>
<!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 id="Head1" runat="server">
<title>Mass Upload</title>
<link href="../upload/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type = "text/javascript">
$(document).ready( function()
{
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader' : '../upload/scripts/uploadify.swf',
'script' : '../cgi-bin/Upload.ashx',
'cancelImg' : '../upload/images/cancel.png',
'folder' : '../upload/temp',
'buttonImg' : '../upload/images/uploadbutton.png',
'width' : '97',
'height' : '22',
'wmode' : 'transparent',
'displayData' : 'speed',
'multi' : true,
'auto' : true,
'simUploadLimit' : 20,
'fileDesc' : 'DWG und SWF - Dateien',
'fileExt' : '*.dwg;*.swf',
'onSelect' : function(event, queueID, fileObj){ EnableObject('FileUpload1');},
'onCancel' : function(event, queueID, fileObj, data){DisableObject('FileUpload1');},
'onComplete' : function(event,queueID,fileObj,response,data){alert(fileObj.name);}
});
$("#startUploadLink").click( function()
{
$('#<%=FileUpload1.ClientID%>').uploadifyUpload();
return false;
});
$("#clearQueueLink").click( function()
{
$("#<%=FileUpload1.ClientID%>").uploadifyClearQueue();
return false;
});
});
</script>
</head>
<body style='background:black;'>
<div id='main'>
<form id="form1" runat="server">
<br/>
<div class="demo">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
Start Upload |
Clear
</div>
</form>
</div>
</body>
</html>
And here's upload.ashx
<%# WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = context.Request("folder")
'If you prefer to use web.config for folder path, uncomment below:
'tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not System.IO.Directory.Exists(savepath) Then
System.IO.Directory.CreateDirectory(savepath)
End If
postedFile.SaveAs((savepath & "\") + filename)
context.Response.Write((tempPath & "/") + filename)
context.Response.StatusCode = 200
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

asp.net placeholder in the head of a page

I have a page that includes javascript which I only want to run under certain conditions. To do this I have placed the scripts into an asp:placeholder
This actually seems to work but when I run a debug on the page I get the following warning.
Element 'placeholder' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing.
If I move the placeholders into the body of the page the warning goes, but that means I'm left with scripts in the body which I also want to avoid. Does anyone have any hints on the best practice for this scenario?? thanks
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='scripts/pageLoadAnimations.js'></scr" & "ipt>"
me.Header.Controls.Add(lt)
End Sub
You can include JS file straight from code behind:
If (some condition is true) Then
Page.ClientScript.RegisterClientScriptInclude("jQuery", "jquery-version.js")
End If
A couple of ways which fit your needs are:
Firstly, you could change your <head> tag to <head id="header" runat="server"> then this allows you to dynamically add anything into it, e.g.
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='pathtojavascriptfile'></script>"
me.Header.Controls.Add(lt)
Or you could create a Public string on your page, then stick the javascript in this.
Public _JS as string
Page_Load
_JS = "alert('here');" ' Or what ever your javascript is
ASPX Page
<head>
<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript">
$().ready(function(){
<%=(me._JS) %>
});
</script>
</head>
You might consider looking into the ClientScriptManager. This will allow you to inject scripts into the header properly using whatever conditions you require.
Including Custom Client Script in ASP.NET Pages
ClientScriptManager Class

Setting ResponseCode manually at CodeBehind fails with IIS7 and 2008 Server

I have developed a web app a year ago aimed to work with IIS6.
Now we are moving to IIS7 and I thought, I'd do some integration tests.
One of this fails:
The web app is more or less a search-engine, giving a 404 or 500 (thanks to your google-advisor ...) when there weren't any results or the data-container is not loaded yet. With IIS6 this worked great: The page output was eg. result.aspx, showing some message and giving back the specified http status (set at codebehind).
Now with IIS7 this behaviour is broken: If I set the http status code at codebehind, my page won't be delivered anymore - instead showing the generic error page of IIS7.
No, I do not want to do any dirty hack with the customErrors-Section ...
I just want the original behaviour back!
Is there any way to do this?
Edit:
Consider following page
<%# Page Language="C#" AutoEventWireup="true"%>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Response.StatusCode = 404;
}
</script>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
This page should be displayed
</div>
</form>
</body>
</html>
Vista + IIS7 = OK
2008 Server + IIS7 = Generic Error Page
have you tried this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
}
HttpResponse.TrySkipIisCustomErrors Property (System.Web)
Your problem is probably that you have tried to set the Status Code (which counts as part of the Header) at some point after you've starting sending the Body of the response i.e. your pages contents - in your case the message.
To solve this you can try setting Response.Buffer to true and then if you have to set a 404/500 response code then call Response.Clear() before setting the response code.
Note that if you are sending a 404/500 then there should generally be no body to the response (although the HTTP spec does allow for it)

Resources