How to check URL existence ?

P

pamelafluente

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
 
M

Matt Kruse

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.
 
P

pamelafluente

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
 
P

pamelafluente

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:
 
L

Laurent Bugnion

Hi,

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/myjavascript/IsUrlActive/check-url.txt

HTH,
Laurent
 
P

pamelafluente

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
 
B

Benjamin

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?
 
P

pamelafluente

I corrected the code for Firefox and Mozilla based browsers too, it now

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?

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("ClickedElement") & " was
clicked")

ElseIf Me.Page.Request.HttpMethod = "POST" Then
Response.Write(Me.Page.Request.Form("ClickedElement") & "
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
 
P

pamelafluente

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
 
P

pamelafluente

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:
 
L

Laurent Bugnion

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
 
L

Laurent Bugnion

Hi,

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
 
P

pamelafluente

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:
 
E

Evertjan.

wrote on 25 aug 2006 in comp.lang.javascript:
Evertjan. ha scritto:

[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!
 
M

Martin Honnen

Laurent Bugnion 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.

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.
 
L

Laurent Bugnion

Hi Martin,

Martin said:
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
 
P

pamelafluente

Hi Laurent,

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

Thank you !!

-pam

Laurent Bugnion ha scritto:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top