By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,680 Members | 1,529 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,680 IT Pros & Developers. It's quick & easy.

How to check URL existence ?

P: n/a
Hi Guys,

I have the following HTML code which is doing a GET to a page, say
MyUrl.aspx :

<body>
<form name="form1" method="get" action="MyUrl.aspx" id="form1">
<input type="hidden" name="ClickedElement" id="Messenger" />
</form>
</body>
where the the Submit() is done within a javascript function invoked at
onclick on some element.

My question is: How can I prevent form submission when MyUrl.aspx is
not available?

The javascript function is:

function Clicked(MyControl)
{
var _CellContent = document.getElementById("Messenger");
_CellContent.value = MyControl.id;
document.form1.submit();
}

Thanks for any help,

Pam

Aug 24 '06 #1
Share this Question
Share on Google+
25 Replies


P: n/a
pa***********@libero.it wrote:
My question is: How can I prevent form submission when MyUrl.aspx is
not available?
Why would a form target url not be available?
Why write the target url to begin with, then? Or is this completely dynamic?

I would say don't just prevent the form from submitting if the target
doesn't exist. Don't even draw the form. Why waste time fillingit out if it
can't be submitted?

Anyway, to answer your question there are a few possibilities. One would be
to use ajax to "GET" the url and see if the server comes back with a 404
error. If not, then submit.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 24 '06 #2

P: n/a
I would say don't just prevent the form from submitting if the target
doesn't exist. Don't even draw the form. Why waste time fillingit out if it
can't be submitted?
Thanks Matt for helping.

It's not a "real" user form. It's only a device to pass some
information from a web page to a server via an asp page in a dynamic
context..
Anyway, to answer your question there are a few possibilities. One would be
to use ajax to "GET" the url and see if the server comes back with a 404
error. If not, then submit.
You are recommending something I am not familiar with at all. I do not
know whether I am able to embark in that... unless the solution is
straightforward.

But... isn't there some simple solution within the realm of javascript?
-Pam
>
--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 24 '06 #3

P: n/a
wrote on 25 aug 2006 in comp.lang.javascript:
But... isn't there some simple solution within the realm of javascript?
<img
src='http://www.?????.com/nonexisting.asp'
style='display:none;'
onerror='alert("Does not exist.")'
onload='alert("Does!")'
>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 24 '06 #4

P: n/a
Hi Evertjan this would be ingenius... if it only worked ! :)

Let's see... I have tried this with various url included itself
("Default.htm") :

<img src="Default.htm" style='display:none;' onerror='alert("Does not
exist.")' onload='alert("Does!")' />

but always says that it does not exists. (?)

Another problem is that this displays at each reload. Is it possible to
transform that in a function returning a boolean variable so that it
can be used to allow or forbid Submit() ?

Thank for the help,

Pam

Evertjan. ha scritto:
wrote on 25 aug 2006 in comp.lang.javascript:
But... isn't there some simple solution within the realm of javascript?

<img
src='http://www.?????.com/nonexisting.asp'
style='display:none;'
onerror='alert("Does not exist.")'
onload='alert("Does!")'

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 24 '06 #5

P: n/a
Hi,

pa***********@libero.it wrote:
You are recommending something I am not familiar with at all. I do not
know whether I am able to embark in that... unless the solution is
straightforward.

But... isn't there some simple solution within the realm of javascript?
-Pam
AJAX is not that complicated. I posted an example of what you want to do
here:

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/

Note the following:
- The code works in IE. I still have an error in Firefox, not sure what
it is, and it's too late now to look for it. Sorry about that.
- The code can only access URLs located on the same server, for security
reasons. If you try to access other domains, you'll need to relax
security on the web client.

The JavaScript code is here:
http://www.galasoft-lb.ch/myjavascri.../check-url.txt

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 24 '06 #6

P: n/a
Thanks Laurent, that's very nice.

Ok I am willing to use it. But keep in mind I know nothing about this
"Ajax" technology (actually I am studying some javascript by a couple
of days). I would need some step by step indication of what I have to
do.

After that I should be able to begin move the first steps in this new
fashinating world.

Thanksvery much for the help.

-pam

Hi,

pa***********@libero.it wrote:
You are recommending something I am not familiar with at all. I do not
know whether I am able to embark in that... unless the solution is
straightforward.

But... isn't there some simple solution within the realm of javascript?
-Pam

AJAX is not that complicated. I posted an example of what you want to do
here:

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/

Note the following:
- The code works in IE. I still have an error in Firefox, not sure what
it is, and it's too late now to look for it. Sorry about that.
- The code can only access URLs located on the same server, for security
reasons. If you try to access other domains, you'll need to relax
security on the web client.

The JavaScript code is here:
http://www.galasoft-lb.ch/myjavascri.../check-url.txt

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 24 '06 #7

P: n/a
Here's the AJAX:
function checkUrl() {
var request = false;
//Firefox and Netscape
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
}
//IE
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", "my/url/that/is/maybe/there");
request.onreadystatechange = function() {
if (request.status == 200 && request.readyState == 4)
{
//page is there
document.myForm.submit();
}
else if (request.status == 404) {
//page is not there
return;
}
}
request.send(null);
}
}
I also I have one question. Why is your script not there sometimes? Why
do you need this?
pa***********@libero.it wrote:
I would say don't just prevent the form from submitting if the target
doesn't exist. Don't even draw the form. Why waste time fillingit out if it
can't be submitted?

Thanks Matt for helping.

It's not a "real" user form. It's only a device to pass some
information from a web page to a server via an asp page in a dynamic
context..
Anyway, to answer your question there are a few possibilities. One would be
to use ajax to "GET" the url and see if the server comes back with a 404
error. If not, then submit.

You are recommending something I am not familiar with at all. I do not
know whether I am able to embark in that... unless the solution is
straightforward.

But... isn't there some simple solution within the realm of javascript?
-Pam

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 25 '06 #8

P: n/a
Laurent Bugnion wrote:
- The code works in IE. I still have an error in Firefox, not sure what
it is, and it's too late now to look for it. Sorry about that.
I corrected the code for Firefox and Mozilla based browsers too, it now
works in IE and FF.

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/
http://www.galasoft-lb.ch/myjavascri.../check-url.txt

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #9

P: n/a
I corrected the code for Firefox and Mozilla based browsers too, it now
works in IE and FF.

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/
http://www.galasoft-lb.ch/myjavascri.../check-url.txt
Ok I will use this last one. Keep me update with your solution. I will
of course acknowledge this contribution in my final application.

By the way, I am new to this stuff: what is that window.XMLHttpRequest.
Is it another parallel communication channel?
Laurent
As to your request of clarification about what I am doing here it is
some more detail (let's keep it simple to focus on logic only):

I have a full featured say "server") application which generates very
beautiful
and complex reports in form of html files (also). These html file are
*extremely*
complicated and could not be done (in practice) as ASP pages. They are
generated in no time through a stringbuilder and brutal writing on disk
of the html code through a streamwriter.

Now, I want add some web interactivity to these html reports. That's
way I am
trying to learn somo javascript. For instance, when one clicks on a
cell a drill
down could occur (etc...). The request is sent to the server (through
the mechanism I
schetcked below) and the html report immediately regenerated to show
the new report (eg, drilled down).

This architecture has 2 advantages (that i can see now):
1. Html reports can be ported wherever and still be used as plain html
(if does not want to interact) HERE also I NEED YOUR FUNCTION so in
case an active version is ported will continue to work!!

2. Reports can be very complex in design and are generated at light
speed.

When the user enter a "drill down/roll up" mode the aspx page which
serves as report processor is copied in the folder where the html page
to be
drilled down resides. HERE I NEED again YOUR FUNCTION

Once the information about the cell that is being drilled/rolled
arrives to
the asp page, there is massive code behinde, which also uses several
web services,
which will deal at light speed with al report regeneration issues and
will redirect
the user to the newly generated report. This is extremely fast.

Here is the detail of my logic. If you have advice they are mot
welcome. As usual.
I do want to do this in a nice and efficient way. The test I have done
so far
shoows that while this solution is simple, it is also very fast and
maintenable.
I am kind of confortable with it. I like things simple and effective.

<script language="javascript" src="MyLib.js"></script>

<!-- ----LOGIC EXAMPLE for Laurent ----->

<div id="Square1" onclick = "Clicked(this)" >
<div style="width: 50px; height: 50px; background-color:green"
onmouseover = "mOver(this)" onmouseout = "mOut(this)" ></div>
</div>

<br />

<div id="Square2" onclick = "Clicked(this)" >
<div style="width: 50px; height: 50px; background-color:red"
onmouseover = "mOver(this)" onmouseout = "mOut(this)" ></div>
</div>

<form name="form1" method="get" action="ReportProcessor.aspx"
id="form1">
<input type="hidden" name="ClickedElement" id="Messenger" />
</form>

</body>

</html>

// JScript File -- MyLib.js ---
function Clicked(MyControl)
{
var _CellContent = document.getElementById("Messenger");
_CellContent.value = MyControl.id;
document.form1.submit();
}

function mOver(MyDiv)
{
PreviousStyle = MyDiv.style.borderStyle;
MyDiv.style.borderStyle = "double";
}
function mOut(MyDiv)
{
MyDiv.style.borderStyle = PreviousStyle;
}

ASPX (ReportProcessor.aspx)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load

<!-- ----LOGIC EXAMPLE for Laurent ----->
If Me.Page.Request.HttpMethod = "GET" Then

Response.Write(Me.Page.Request.QueryString("Clicke dElement") & " was
clicked")

ElseIf Me.Page.Request.HttpMethod = "POST" Then
Response.Write(Me.Page.Request.Form("ClickedElemen t") & "
was clicked")

Else

Response.Write("Unexpected Method " &
Me.Page.Request.HttpMethod)

End If

'here i get the information about the action being performed by the
user on the HTML
'report and regenerate it accordingly. The report is written brutally
on the hard disk
'through a sreamwriter. This is extremely fast (a few seconds even for
millions report cells).
'Then redirect the user to the newly generated report
'
End Sub

-Pam

Aug 25 '06 #10

P: n/a
Hi Laurent.
Ok I am trying to incorporate your function in my program.

It still need some debugging. You need to place the correct return
values. I tried but does not seem to work as is.

I see a place where you need a throw. Also I need to know how to catch
the exception in my calling function

I invent. Let me know the right way to do the catch

function Clicked(MyControl)
{
var _CellContent = document.getElementById("Messenger");
_CellContent.value = MyControl.id;

// How do I write a TRY CACTH FINALLY statement in javascripr
// to catch your exceptions. If not possible return TRUE

try
if (isUrlActive("ReportProcessor.aspx"))
document.form1.submit();
}
catch

// inform use about issue
finally
// whatever cleaning
end try

------- some notes here: please check return values an throw where
necessary

function isUrlActive( strUrl )
{
var oHttp = null;
if ( window.ActiveXObject )
{
oHttp = new window.ActiveXObject( "Microsoft.XMLHTTP" );
}
else
{
if ( window.XMLHttpRequest )
{
oHttp = new window.XMLHttpRequest();
}
else
{
throw "UNSUPPORTED PLATFORM";
}
}
if ( !oHttp )
{
throw "ERROR";
}
oHttp.open( "GET", strUrl, true );
oHttp.setRequestHeader( "Content-Type", "text/html; charset=utf-8" );

oHttp.onreadystatechange = function()
{
var bDummy = true; //is this unused?

if ( oHttp.readyState == 4 )
{
if ( oHttp.status == 200 )
{
// alert( "Server replied OK" );

return true; //<-------------------------------
}
else
{
// alert( "There was a problem: " + oHttp.status );
// THROW something here! (or return true) !!<--------------------

return true;

}
}
}

//what is this?

oHttp.send( null );
return true; //<--------------
}
Anyway, beautiful! Thanks!

-Pam

Aug 25 '06 #11

P: n/a
Sorry Benjamin!!

I got mixed up. My message 10 was meant to address YOUR question, not
Laurent's.

(Anyway I will clear it up in my acknow!)

Message 11 points out some refinements that are needed to the function
to make it work.

Sorry again. Thanks a lot.

-Pam

Benjamin ha scritto:
Here's the AJAX:
function checkUrl() {
var request = false;
//Firefox and Netscape
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
}
//IE
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", "my/url/that/is/maybe/there");
request.onreadystatechange = function() {
if (request.status == 200 && request.readyState == 4)
{
//page is there
document.myForm.submit();
}
else if (request.status == 404) {
//page is not there
return;
}
}
request.send(null);
}
}
I also I have one question. Why is your script not there sometimes? Why
do you need this?
pa***********@libero.it wrote:
I would say don't just prevent the form from submitting if the target
doesn't exist. Don't even draw the form. Why waste time fillingit out if it
can't be submitted?
Thanks Matt for helping.

It's not a "real" user form. It's only a device to pass some
information from a web page to a server via an asp page in a dynamic
context..
Anyway, to answer your question there are a few possibilities. One would be
to use ajax to "GET" the url and see if the server comes back with a 404
error. If not, then submit.
You are recommending something I am not familiar with at all. I do not
know whether I am able to embark in that... unless the solution is
straightforward.

But... isn't there some simple solution within the realm of javascript?
-Pam
>
--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 25 '06 #12

P: n/a
:oops: was 9, 11 was 10 !
Sorry Benjamin!!
Aug 25 '06 #13

P: n/a
Hi,

Not totally correct. See, the call to the remote URL is asynchronous. It
means that you send the message, then the JavaScript processing
continues, and then later a response comes (success or error). So you
need to think slightly differently.

You can also use XmlHttpRequest synchronously, but I recommend against
it, because as long as the response didn't arrive, the whole JavaScript
engine is blocked.

As for the try..catch, unfortunately it varies. You don't catch an
Exception object (or a derived class) like in C#; in JavaScript, you can
throw strings or any other object. Here, I throw strings, so you can
catch them and alert them, for example.

I suggest something along these lines (the "..." are meant for
additional HTML or JavaScript code needed for your functions):

....
var bUrlIsActive = false;
var bUrlError = false;
....

<body onload="checkUrl();">

....

function checkUrl()
{
try
{
isUrlActive( 'ReportProcessor.aspx' );
}
catch ( strError )
{
alert( strError );
}
}

function Clicked( MyControl )
{
var _CellContent = document.getElementById("Messenger");
_CellContent.value = MyControl.id;

// Here, I would disable the button
submitForm();
}

var timerSubmitForm = null;

function submitForm()
{
// Check if a timer is already running. If yes, cancel it
if ( timerSubmitForm != null )
{
clearTimeout( timerSubmitForm );
timerSubmitForm = null;
}

// Check if the flags are set
if ( bUrlIsActive )
{
// Everything OK, submit form
document.form1.submit();
return;
}

if ( bUrlError )
{
alert( "Sorry, unable to process your form. Try again later" );
// Try again to check if the URL is active now
checkUrl();
return;
}

// Both flags are false, means that the response didn't arrive yet
setTimeout( submitForm, 500 ); // Try again 500 ms later
}

function isUrlActive( strUrl )
{
bUrlIsActive = false;
bUrlError = false;

var oHttp = null;
if ( window.ActiveXObject )
{
oHttp = new window.ActiveXObject( "Microsoft.XMLHTTP" );
}
else
{
if ( window.XMLHttpRequest )
{
oHttp = new window.XMLHttpRequest();
}
else
{
throw "Unsupported platform";
}
}
if ( !oHttp )
{
throw "Undefined error";
}
oHttp.open( "GET", strUrl, true ); // true = async, false = sync
oHttp.setRequestHeader( "Content-Type", "text/html; charset=utf-8" );

oHttp.onreadystatechange = function()
{
if ( oHttp.readyState == 4 )
{
if ( oHttp.status == 200 )
{
bUrlIsActive = true;
bUrlError = false;
}
else
{
bUrlIsActive = false;
bUrlError = true;
}
}
}
oHttp.send( null );
}

Please tell me if something is unclear.

HTH,
Laurent

pa***********@libero.it wrote:
Hi Laurent.
Ok I am trying to incorporate your function in my program.

It still need some debugging. You need to place the correct return
values. I tried but does not seem to work as is.

I see a place where you need a throw. Also I need to know how to catch
the exception in my calling function

I invent. Let me know the right way to do the catch
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #14

P: n/a
Hi,

pa***********@libero.it wrote:
>>I corrected the code for Firefox and Mozilla based browsers too, it now
works in IE and FF.

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/
http://www.galasoft-lb.ch/myjavascri.../check-url.txt


Ok I will use this last one. Keep me update with your solution. I will
of course acknowledge this contribution in my final application.
If you want, but it's not necessary. AJAX code is available in many
places on the web, I didn't invent anything.
By the way, I am new to this stuff: what is that window.XMLHttpRequest.
Is it another parallel communication channel?
Not really. It's an object which the browser offers, allowing to send
HTTP requests along the normal HTTP communication channel. The advantage
of XmlHttpRequest is that you can send such requests without causing the
page to refresh, which you can't if you just type a URL in the location
bar. Also, this object is fairly standardized (actually, it's been
available in browsers since 1997).

There is a lot of hype lately about AJAX, which means Asynchronous
JavaScript and XML. The XmlHttpRequest is the object you use to send
such requests and handle the responses. Typically you will have XML
content (for example SOAP formatted requests/responses), but actually
everything is possible (HTML, text, whatever), so the name
XmlHttpRequest might be slightly confusing. Also, XmlHttpRequest allow
to send synchronous requests, though it's not a good idea. So in theory
you could do some SJAX (synchronous JavaScript and XML), some AJAT
(asynch javascript and text) etc... Of course it's less sexy than AJAX.

Note also that XmlHttpRequest is not the only object allowing you to
send "invisible" requests to a server. The Image object, when its "src"
attribute is set, also sends a request. The Response will be interpreted
as an Image and stored. If you want to just "ping" a server and you
don't care about the response at all (for example to notify a server
that a page is still open), you could just do

var myImage = new Image();
myImage.src = "i-am-alive.aspx";

Some say that AJAX is the future of the web, some say that it's not. Me,
I think that when Microsoft invests big big bucks to supply programmers
with a free framework based on AJAX and cross-browser compatible (that's
ATLAS running on ASP.NET), then it's likely that the technology is going
to boom...

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #15

P: n/a
Dear Laurent,

What I wish to achieve is a possibly silent handling of the missing
URL. If the url is missing it's fine, it may be because the user is
using the page as simple html report and he needs no interaction. I may
just set a small label to inform him.
As I told you there is NO submit button. That is an hidden form to talk
with the ASP page. The message is passed to the ASP page on some event
like onclick
I would like to have your function in the following way, if possible.

- The function should be a pure boolean function that return TRUE/FALSE
according
the existence of URL.

-Should not make any alert. In case of possible errors, just throw
exceptions that I can choose to handle, if I want (ot I may simply
ignore it). No open windows.

This way it can be used in a more modular way. If I want to tell
something to the user, I do it outside the function.

Could you make these changes. Or I might try to make them and you could
revise the final version....
Notes:

1.
<body onload="checkUrl();">
I want the check to be done on the event. I imagine a completely
dinamic situation where the report processor .ASPX could appear anytime
in a folder.
2.
function Clicked( MyControl )
{
var _CellContent = document.getElementById("Messenger");
_CellContent.value = MyControl.id;

// Here, I would disable the button

---the is no button: it's a hidden field, URLExists shold not rise
any alert

if function URLExists()
submitForm();
else

---- want to set a silent label to inform there will be no
interaction

end if

}

3. Remove all alerts from function. Replace with exception raising.
Return explicitly true/false on ALL exit pattern

4. After some throw (eg throw "Undefined error";) would place some
return for more clarity

5. if ( oHttp.readyState == 4 ) you are not handling the else. For
clarity I would add it explicitly.

Thanks for all the info. This stuff is really fashinating. I think I
will be spending a lot of time on it...

Finally, what do you think of my schem to pass information
HTML-->ASP.NET do you see any improment I can make?
** Thanks a lot **
-Pam
Laurent Bugnion ha scritto:
Hi,

pa***********@libero.it wrote:
>I corrected the code for Firefox and Mozilla based browsers too, it now
works in IE and FF.

http://www.galasoft-lb.ch/myjavascript/IsUrlActive/
http://www.galasoft-lb.ch/myjavascri.../check-url.txt

Ok I will use this last one. Keep me update with your solution. I will
of course acknowledge this contribution in my final application.

If you want, but it's not necessary. AJAX code is available in many
places on the web, I didn't invent anything.
By the way, I am new to this stuff: what is that window.XMLHttpRequest.
Is it another parallel communication channel?

Not really. It's an object which the browser offers, allowing to send
HTTP requests along the normal HTTP communication channel. The advantage
of XmlHttpRequest is that you can send such requests without causing the
page to refresh, which you can't if you just type a URL in the location
bar. Also, this object is fairly standardized (actually, it's been
available in browsers since 1997).

There is a lot of hype lately about AJAX, which means Asynchronous
JavaScript and XML. The XmlHttpRequest is the object you use to send
such requests and handle the responses. Typically you will have XML
content (for example SOAP formatted requests/responses), but actually
everything is possible (HTML, text, whatever), so the name
XmlHttpRequest might be slightly confusing. Also, XmlHttpRequest allow
to send synchronous requests, though it's not a good idea. So in theory
you could do some SJAX (synchronous JavaScript and XML), some AJAT
(asynch javascript and text) etc... Of course it's less sexy than AJAX.

Note also that XmlHttpRequest is not the only object allowing you to
send "invisible" requests to a server. The Image object, when its "src"
attribute is set, also sends a request. The Response will be interpreted
as an Image and stored. If you want to just "ping" a server and you
don't care about the response at all (for example to notify a server
that a page is still open), you could just do

var myImage = new Image();
myImage.src = "i-am-alive.aspx";

Some say that AJAX is the future of the web, some say that it's not. Me,
I think that when Microsoft invests big big bucks to supply programmers
with a free framework based on AJAX and cross-browser compatible (that's
ATLAS running on ASP.NET), then it's likely that the technology is going
to boom...

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #16

P: n/a
wrote on 25 aug 2006 in comp.lang.javascript:
>
Evertjan. ha scritto:
>wrote on 25 aug 2006 in comp.lang.javascript:
But... isn't there some simple solution within the realm of
javascript?

<img
src='http://www.?????.com/nonexisting.asp'
style='display:none;'
onerror='alert("Does not exist.")'
onload='alert("Does!")'
>
[please do not toppost on usenet]

Hi Evertjan this would be ingenius... if it only worked ! :)
You are right,
it needs to receivea picture file to work,
independent of the extension.
Another problem is that this displays at each reload.
No, it does not, see the css I added.
Is it possible to
transform that in a function returning a boolean variable so that it
can be used to allow or forbid Submit() ?
Yes, as long as you wait testing the variable till the onerror or the
onload has fired.

Something like this, perhaps:

<img
src='http://www.?????.com/existing.jpg'
style='display:none;'
onerror='existing = false'
onload='existing = true'
>
<script type='text/javascript'>
var existing = "waiting"

function test(){
if (existing != "waiting")
decideIfToDoSubmit()
else
setTimeout('test()',100)
}

test()

</script>
NOT TESTED!

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 25 '06 #17

P: n/a


Laurent Bugnion wrote:

http://www.galasoft-lb.ch/myjavascri.../check-url.txt
A HTTP HEAD request instead of the GET should suffice to get the HTTP
status.
And as IE 7 is going to have XMLHttpRequest I would change the sequence
of checks to test for window.XMLHttpRequest first and then
window.ActiveXObject second.

And why are you doing
oHttp.setRequestHeader( "Content-Type", "text/html; charset=utf-8" );
on a GET request? That header denotes the MIME type of any request body
but a GET request has no request body at all.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 25 '06 #18

P: n/a
Hi Martin,

Martin Honnen wrote:
A HTTP HEAD request instead of the GET should suffice to get the HTTP
status.
And as IE 7 is going to have XMLHttpRequest I would change the sequence
of checks to test for window.XMLHttpRequest first and then
window.ActiveXObject second.
Great suggestion, thanks.
And why are you doing
oHttp.setRequestHeader( "Content-Type", "text/html; charset=utf-8" );
on a GET request? That header denotes the MIME type of any request body
but a GET request has no request body at all.
That's correct. I actually converted a POST request with SOAP content
(text/xml) to this small example for Pamela, and it was very late, so I
didn't think straight.

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #19

P: n/a
Hi Laurent,

I am looking forward to the *final* release, then.

Thank you !!

-pam

Laurent Bugnion ha scritto:
Hi Martin,

Martin Honnen wrote:
A HTTP HEAD request instead of the GET should suffice to get the HTTP
status.
And as IE 7 is going to have XMLHttpRequest I would change the sequence
of checks to test for window.XMLHttpRequest first and then
window.ActiveXObject second.

Great suggestion, thanks.
And why are you doing
oHttp.setRequestHeader( "Content-Type", "text/html; charset=utf-8" );
on a GET request? That header denotes the MIME type of any request body
but a GET request has no request body at all.

That's correct. I actually converted a POST request with SOAP content
(text/xml) to this small example for Pamela, and it was very late, so I
didn't think straight.

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 25 '06 #20

P: n/a
Hi,

pa***********@libero.it wrote:
Hi Laurent,

I am looking forward to the *final* release, then.

Thank you !!

-pam
I posted the corrected version according to Martin's suggestions.

Demo:
http://www.galasoft-lb.ch/myjavascript/IsUrlActive/

Code:
http://www.galasoft-lb.ch/myjavascri.../check-url.txt

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 26 '06 #21

P: n/a
Hi,

pa***********@libero.it wrote:
Dear Laurent,

What I wish to achieve is a possibly silent handling of the missing
URL. If the url is missing it's fine, it may be because the user is
using the page as simple html report and he needs no interaction. I may
just set a small label to inform him.
That's good. Just replace the "alert" code with some DOM interaction to
set the label.

Typically, I use spans for that:

<span id="spanStatus">&nbsp;</span>

and then

function setStatus( strMessage )
{
document.getElementById( "spanStatus" ).firstChild.nodeValue
= strMessage;
}
As I told you there is NO submit button. That is an hidden form to talk
with the ASP page. The message is passed to the ASP page on some event
like onclick
Yes. It doesn't really make a difference when or how the method is called.
I would like to have your function in the following way, if possible.

- The function should be a pure boolean function that return TRUE/FALSE
according
the existence of URL.
As I said already, it's not a good idea. Synchronous AJAX calls are
really not recommended. I would really reconsider if I were you. My code
suggestion is asynchronous, so it won't block anything (animations,
etc...), and it will be more user-friendly.

-Should not make any alert. In case of possible errors, just throw
exceptions that I can choose to handle, if I want (ot I may simply
ignore it). No open windows.
Ignoring an exception will cause the browser to stop execution and to
display a message box. Not a good idea.

This way it can be used in a more modular way. If I want to tell
something to the user, I do it outside the function.

Could you make these changes. Or I might try to make them and you could
revise the final version....
I prefer that you do the changes, post the code here and let us comment.
That's more in the educating spirit of this newsgroup ;-)

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 26 '06 #22

P: n/a
I prefer that you do the changes, post the code here and let us comment.
That's more in the educating spirit of this newsgroup ;-)

Greetings,
Laurent
Beautiful !!! Thanks Laurent, you are really great!
(By the way I am happily using the VS debugger as you suggested)

I am going to make some unessential changes to adapt it to my specific
situation and I am gonna ask you if that could be OK.

Will post it in a while...

Thanks again.

-Pam

Aug 27 '06 #23

P: n/a
Typically, I use spans for that:
>
<span id="spanStatus">&nbsp;</span>

and then

function setStatus( strMessage )
{
document.getElementById( "spanStatus" ).firstChild.nodeValue
= strMessage;
}
Beautiful idea, I will use it. Can I also use a DIV ? I would prefer.
Same syntax?
Here is my adjusted version. I want to check before submitting.
I undestood the async nature of this call. Therefore I placed the
submission on the callback. Hope is fine.

Here is complete source code of a demo: HTML / AJAX (yours) / ASP.NET
watch out for line breaks

I wait for you comment / suggestion / corrections...

** THANKS a LOT **

-Pam
========== HTML InteractiveReport_Demo.htm

<!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>
<title>Interactive Report Demo</title>

<style type="text/css" media="screen">

..c1bg{position:absolute;background:#F0FFF0;border-width:1px;border-style:outset;}
..c1fg{position:absolute;border-width:0;color:#000000;background:transparent;text-align:left;font-family:Tahoma;font-size:11px;font-weight:bold;}
..c3bg{position:absolute;background:#FFFFF0;border-width:1px;border-style:outset;}
..c3fg{position:absolute;border-width:0;color:#008000;background:transparent;text-align:left;font-family:Tahoma;font-size:11px;font-weight:bold;}

</style>

</head>
<body>

<script language="javascript" src="Ajax_Javascript.js"></script>

<!--Messenger form to send the information about the clicked cell to
the ASP page which processes the request-->
<form name="form1" method="get" action="ReportProcessor.aspx"
id="form1">
<input type="hidden" name="ClickedElement" id="MessengerInput"
/>
</form>

<!--2 Examples of cells: on click their ID is passed to the ASP page
for processing (Drill Down / Roll Up) -->
<!--Need to place a cell context menu to differentiate between diffent
actions: Drill / Roll /etc.-->
<div id ="16,0" onclick = "Clicked(this)">
<div class=c3bg
style="top:372px;left:127px;width:88px;height:203p x;"></div><div
class=c3fg style="top:374px;left:129px;"><table><tr><td width=82px
height=197px valign=middle>Brazil</td></tr></table></div>
</div>
<div id ="5,0" onclick = "Clicked(this)">
<div class=c1bg
style="top:280px;left:127px;width:88px;height:42px ;"></div><div
class=c1fg style="top:282px;left:129px;"><table><tr><td width=82px
height=36px valign=middle>Austria</td></tr></table></div>
</div>
<span id="StatusInfo">&nbsp;</span>
</body>
</html>
================= AJAX Ajax_Javascript.js
// JScript File: Ajax_Javascript.js

//http://groups.google.it/group/comp.lang.javascript/browse_frm/thread/b3b8fa7bad9223a4?hl=it
//Laurent Bugnion, GalaSoft
function setStatus( strMessage )
{
document.getElementById("StatusInfo").firstChild.n odeValue =
strMessage;
}
var SubmitURL;

function Clicked(MyControl)
{
var CellID = document.getElementById("MessengerInput");
CellID.value = MyControl.id; //value communicated
SubmitURL = CellID.form.action ;
SubmitOnlyIfUrlActive();
}
var oHttp = null;

function SubmitOnlyIfUrlActive()
{
if ( window.XMLHttpRequest )
{
oHttp = new window.XMLHttpRequest();
}
else
{
if ( window.ActiveXObject )
{
oHttp = new window.ActiveXObject("Microsoft.XMLHTTP" );
}
else
{
setStatus("Unsupported Platform");
}
}
if ( !oHttp )
{
setStatus("Error");
}
oHttp.open("HEAD", SubmitURL, true ); // true = async, false = sync
oHttp.onreadystatechange = CallBack
oHttp.send( null );
}
function CallBack()
{
if ( oHttp.readyState == 4 )
{
if ( oHttp.status == 200 )
{
document.form1.submit()
}
else
{
if (oHttp.status == 404)
{
setStatus( SubmitURL + " Not Found");
}
else
{
setStatus("Error: " + oHttp.status );
}
}
}
}

======= ASP.NET ReportProcessor.aspx
Partial Class ReportProcessor
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load

If Me.Page.Request.HttpMethod = "GET" Then

Response.Write(Me.Page.Request.QueryString("Clicke dElement") & " was
clicked")

ElseIf Me.Page.Request.HttpMethod = "POST" Then
Response.Write(Me.Page.Request.Form("ClickedElemen t") & "
was clicked")

Else

Response.Write("Unexpected Method " &
Me.Page.Request.HttpMethod)

End If

End Sub

End Class

Aug 27 '06 #24

P: n/a
Hi,

pa***********@libero.it wrote:
>>Typically, I use spans for that:

<span id="spanStatus">&nbsp;</span>

and then

function setStatus( strMessage )
{
document.getElementById( "spanStatus" ).firstChild.nodeValue
= strMessage;
}

Beautiful idea, I will use it. Can I also use a DIV ? I would prefer.
Same syntax?
DIVs also work, yes. I use spans because they are easier to place in an
existing layout. One thing you should be careful of: Make sure to have
no carriage return between the DIV tag and the &nbsp; This is to avoid
problems in Firefox, where carriage returns are regarded as a child node
(text) of the DIV parent node. So then firstChild is not the &nbsp;
anymore, but is the '\n\r' text node.

It's possible to make the script more robust to handle this kind of
things, but if you use ASP.NET to produce your HTML code anyway, it's
also easy to make the HTML code look exactly like you need.
Here is my adjusted version. I want to check before submitting.
I undestood the async nature of this call. Therefore I placed the
submission on the callback. Hope is fine.

Here is complete source code of a demo: HTML / AJAX (yours) / ASP.NET
watch out for line breaks

I wait for you comment / suggestion / corrections...
I think that the code will work. I didn't test it though. A few comments:

1) The submit action will be tried only once. I gather from previous
posts that it is what you want, right?

2) Checking if the URL is active might take a little time, so it is
customary in AJAX to inform the user about the action taking place. You
can use the status "label" for this.

3) JavaScript uses other coding conventions than C#. In fact, it uses
the Java conventions (thought it has nothing to do with Java). You might
want to correct the code, for example using camel notation for method
names (clicked() instead of Clicked(), submitOnlyIfUrlActive(), ..)

4) For clarity, it is customary to name callback methods according to
the name of the method which initiated the call. In your case, I would
rename the "Callback()" method to "submitOnlyIfUrlActiveCallback()".

5) It is good practice to end JavaScript statements with ';', though
it's not absolutely necessary.

6) I see that you use VB.NET for the server-side logic... I would really
consider switching to C# if I were you. Amongst the many, many
advantages that C# has over VB.NET, the syntax is very similar to
JavaScript, so it's easier to switch from one to the other.

I suppose that you tested the code and that it works, so I didn't
perform a functionality test.
** THANKS a LOT **

-Pam
Prego ;-)
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 27 '06 #25

P: n/a
DIVs also work, yes. I use spans because they are easier to place in an
existing layout. One thing you should be careful of: Make sure to have
no carriage return between the DIV tag and the &nbsp; This is to avoid
problems in Firefox, where carriage returns are regarded as a child node
(text) of the DIV parent node. So then firstChild is not the &nbsp;
anymore, but is the '\n\r' text node.
Good to know that.
It's possible to make the script more robust to handle this kind of
things, but if you use ASP.NET to produce your HTML code anyway, it's
also easy to make the HTML code look exactly like you need.
Yes it's immediate. Just change html strings in the generator.
2) Checking if the URL is active might take a little time, so it is
customary in AJAX to inform the user about the action taking place. You
can use the status "label" for this.
I added that, but placed after "HEAD" (see below). Also change the
position
where the callback event handler is attached.
3) JavaScript uses other coding conventions than C#. In fact, it uses
the Java conventions (thought it has nothing to do with Java). You might
want to correct the code, for example using camel notation for method
names (clicked() instead of Clicked(), submitOnlyIfUrlActive(), ..)
Good to know that. Changed all to "prefix - camel" notation notation
(did some little search :) ).
4) For clarity, it is customary to name callback methods according to
the name of the method which initiated the call. In your case, I would
rename the "Callback()" method to "submitOnlyIfUrlActiveCallback()".
Very nice.
5) It is good practice to end JavaScript statements with ';', though
it's not absolutely necessary.
Right.
6) I see that you use VB.NET for the server-side logic... I would really
consider switching to C# if I were you. Amongst the many, many
advantages that C# has over VB.NET, the syntax is very similar to
JavaScript, so it's easier to switch from one to the other.
:) I know. For me it is easier, as I do not have { } on my keyboard
(IT). To me vb is more
readable than c. Anyway could live with C# also.
I suppose that you tested the code and that it works, so I didn't
perform a functionality test.
Tested with both Firefox and IE. Response from ASP page with Firefox
seems (slighly) quicker.
>
Prego ;-)
Laurent
Here is the list of changes with revised source code:
** changed notation:
prefix - camel notation
** added ";"
oHttp.onreadystatechange = submitOnlyIfUrlActiveCallback;
document.form1.submit();
** why this does not follow the above notation ??
onreadystatechange
** change position (before "head"):
oHttp.onreadystatechange = submitOnlyIfUrlActiveCallback
it does not seem to make much sense to place it after "head" (??) we
cannot relay on the slowness of the net :)
** added before head:
setStatus( "Checking existence of report processor " + submitURL + "
....");
(I have the impression this slows down submission, is it possible?
so I placed after "head" because anyway async to avoid delay of
drawstring)
//========== CODE
function setStatus( strMessage )
{
document.getElementById("statusInfo").firstChild.n odeValue =
strMessage;
}
var submitURL;

function Clicked(MyControl)
{
var CellID = document.getElementById("messengerInput");
CellID.value = MyControl.id; //value communicated
submitURL = CellID.form.action;
submitOnlyIfUrlActive();
}

var oHttp = null;

function submitOnlyIfUrlActive()
{
if ( window.XMLHttpRequest )
{
oHttp = new window.XMLHttpRequest();
}
else
{
if ( window.ActiveXObject )
{
oHttp = new window.ActiveXObject("Microsoft.XMLHTTP" );
}
else
{
setStatus("Unsupported Platform");
}
}
if ( !oHttp )
{
setStatus("Error");
}
oHttp.onreadystatechange = submitOnlyIfUrlActiveCallback;
oHttp.open("HEAD", submitURL, true ); // true = async, false = sync

setStatus( "Checking existence of report processor " + submitURL + "
....");
oHttp.send( null );
}

function submitOnlyIfUrlActiveCallback()
{
if ( oHttp.readyState == 4 )
{
if ( oHttp.status == 200 )
{
document.form1.submit();
}
else
{
if (oHttp.status == 404)
{
setStatus( submitURL + " Not Found");
}
else
{
setStatus("Error: " + oHttp.status );
}
}
}
}

=========== new status label in HTML page
<div id="statusInfo">&nbsp;</span>
Thank you.
-Pam

Aug 27 '06 #26

This discussion thread is closed

Replies have been disabled for this discussion.