Page 1 of 2 12 LastLast
Results 1 to 10 of 14

Thread: Redirect to a page if found

  1. #1
    Join Date
    Nov 2005
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Redirect to a page if found

    Hi,
    I'm after a script to load a page if it is found, if not, continue to load the current page.

    EG:
    index.html
    upon opening checks if index2.html is on the server.
    if it is, then load that instead of index.html.
    Else, continue on loading index.html

    Regards
    Craig

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I came across this code somewhere in my travels and though I don't understand it fully, it looks like what you are after:

    Code:
    function getFile(filename)
      { oxmlhttp = null;
        try
          { oxmlhttp = new XMLHttpRequest();
            oxmlhttp.overrideMimeType("text/xml");
          }
        catch(e)
          { try
              { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
            catch(e)
              { return null;
              }
          }
        if(!oxmlhttp) return null;
        try
          { oxmlhttp.open("GET",filename,false);
            oxmlhttp.send(null);
          }
        catch(e)
          { return null;
          }
        return oxmlhttp.responseText;
      }
    It is actually meant to retrieve the contents of a file for use elsewhere in your code but, it will return null if the file isn't there. I think it will only work on the same domain as the page it is looking for but, according to you, that is all you need. The way to use it would be to put it in a script block in the head of your page and then just after it in the same script bock have:

    Code:
    if (getFile('index2.html')!==null)
    window.location.replace('index2.html')
    Put this all together and you've got:

    Code:
    <script type="text/javascript">
    function getFile(filename)
      { oxmlhttp = null;
        try
          { oxmlhttp = new XMLHttpRequest();
            oxmlhttp.overrideMimeType("text/xml");
          }
        catch(e)
          { try
              { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
            catch(e)
              { return null;
              }
          }
        if(!oxmlhttp) return null;
        try
          { oxmlhttp.open("GET",filename,false);
            oxmlhttp.send(null);
          }
        catch(e)
          { return null;
          }
        return oxmlhttp.responseText;
      }
    
    if (getFile('index2.html')!==null)
    window.location.replace('index2.html')
    
    </script>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Aug 2004
    Posts
    10,143
    Thanks
    3
    Thanked 1,008 Times in 993 Posts
    Blog Entries
    16

    Default

    Nice thinking John. I was just about to type up something similar, since Ajax was the only way I could think of that might work here. I haven't tested your code yet, but at a glance it looks like it should work.

  4. #4
    Join Date
    Nov 2005
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thanks guys.
    I have just tried it and it works great.
    Thanks again for your help.

    Regards
    Craig

  5. #5
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1
    I came across this code somewhere in my travels and though I don't understand it fully, it looks like what you are after
    It'll work, but it's not best suited for the task as it's designed to obtain, and return, XML from the server.

    If the XMLHttpRequest approach is taken then, in principle, it would best to perform a HEAD request and check the response. As a HEAD HTTP request only returns the headers that the server would normally send with a complete response, this method is quick and efficient. Unfortunately, earlier implementations of the XMLHttpRequest object in some browsers (most notably Safari) don't support HEAD requests. As I can't test how they respond, it may be wise to avoid this and use GET, despite the advantages. If, however, the behaviour is only the same as a GET request, then HEAD should still be used.

    Irrespective of the transfer method, it is the response code that is important. As servers will respond to errors by sending plain or hypertext notes, the responseText property will not be null or empty except in extremely rare occasions. Though the OP reported success, I doubt it was well tested, because it fails here.

    It is actually meant to retrieve the contents of a file for use elsewhere in your code but, it will return null if the file isn't there.
    No, it won't. It will return null if that is the value of the responseText property, or if an exception is thrown when the open or send methods are called (which I don't even think is possible). If the file doesn't exist, the server will send a 404 response and return the usual File Not Found entity so responseText will be a string.

    I think it will only work on the same domain as the page it is looking for [...]
    It will only connect to the server that sent the current document, which is what I think you meant to say. That is a security issue, similar to the same origin policy for scripts that try to interact with frames.

    The example below assumes that the server will only return a 404 error response for the failure condition. Other responses, such as 403 Forbidden, will require (minor) modifications.

    Code:
    var global = this;
    
    function getRequestObject() {
      var request = null;
    
      if( ('object'   == typeof global.XMLHttpRequest)
       || ('function' == typeof global.XMLHttpRequest))
      {
        request = new XMLHttpRequest();
      } else if('function' == typeof global.ActiveXObject) {
        /*@cc_on @*/
        /*@if(@_jscript_version >= 5)
          try {
            request = new ActiveXObject('Msxml2.XMLHTTP');
          } catch(e) {
            try {
              request = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(e) {
              request = null;
            }
          }
          @end @*/
      }
      return (request && ('object' == typeof request))
        ? request
        : null;
    }
    
    var httpRequest = getRequestObject(),
        url = 'http://www.example.com/index2.html';
    
    if(httpRequest) {
      httpRequest.open('HEAD', url, false);
      httpRequest.send(null);
    
      if(404 != httpRequest.status) {
        location.replace(url);
      }
    }
    All that said, this whole approach is less than reliable, not least because not only will it rely on client-side scripting, but also on a feature that isn't implemented everywhere. If a server-side language (like PHP) is available, this can be done much better and quicker on the server.

    Mike

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    To narrow things down from a different angle, one could test the output for a string that would only be on the page if it is there:

    Code:
    <script type="text/javascript">
    function getFile(filename)
      { oxmlhttp = null;
        try
          { oxmlhttp = new XMLHttpRequest();
            oxmlhttp.overrideMimeType("text/xml");
          }
        catch(e)
          { try
              { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
            catch(e)
              { return null;
              }
          }
        if(!oxmlhttp) return null;
        try
          { oxmlhttp.open("GET",filename,false);
            oxmlhttp.send(null);
          }
        catch(e)
          { return null;
          }
        return oxmlhttp.responseText;
      }
    
    if (getFile('index2.html')&&getFile('index2.html').indexOf('Welcome to Index2')!==-1)
    window.location.replace('index2.html')
    
    </script>
    Last edited by jscheuer1; 11-29-2005 at 08:57 AM.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Mike's solution is more efficient, as John's involves downloading the entire page.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I think I agree, Twey (having trouble following Mike's elegant code again). However, my method avoids the issues of Safari possibly not liking the HEAD request and the possibility that something other than what is expected may be returned for a missing page. Instead of testing for a 'missing' response over which we have no control and can only guess, it tests for a known string on the sought after page.

    After seeing what Opera makes of my code (nothing), I tend to agree with Mike when he says:

    Quote Originally Posted by Mike
    If a server-side language (like PHP) is available, this can be done much better and quicker on the server.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Nov 2005
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thanks for the quick responses.
    I dont have access to any server side scripting. I am running this on an embeded microcontroller that i wrote the code for.

    I have not done any html programming in any language so i asked here.

    I have seen all of the examples and to me they look good. I was wondering if there is a way to check to see if a file is physically there?

    Thanks for your help.

    Regards
    Craig

  10. #10
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Of course a server-side language would be better if available. I would, if I were you, use both in conjunction with one another:
    Code:
    var global = this;
    
    function getRequestObject() {
      var request = null;
    
      if( ('object'   == typeof global.XMLHttpRequest)
       || ('function' == typeof global.XMLHttpRequest))
      {
        request = new XMLHttpRequest();
      } else if('function' == typeof global.ActiveXObject) {
        /*@cc_on @*/
        /*@if(@_jscript_version >= 5)
          try {
            request = new ActiveXObject('Msxml2.XMLHTTP');
          } catch(e) {
            try {
              request = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(e) {
              request = null;
            }
          }
          @end @*/
      }
      return (request && ('object' == typeof request))
        ? request
        : null;
    }
    
    var httpRequest = getRequestObject(),
        url = 'http://www.example.com/index2.html';
    
    if(httpRequest) {
      try {
        httpRequest.open('HEAD', url, false);
      } catch(e) {
        httpRequest.open('GET', url, false);
      }
      httpRequest.send(null);
    
      if(404 != httpRequest.status) {
        location.replace(url);
      }
    }
    ... thus incorporating the features of both. Notes:
    - I don't have any experience of handling exceptions in Javascript, so I'm using the Java approach (as minimally as possible);
    - I'm assuming that Safari's XMLHttpRequest object will throw an exception if one attempts to use HEAD;
    - What on earth are those /*@ things? A form of conditional comment for Javascript?
    I was wondering if there is a way to check to see if a file is physically there?
    By which you mean what? Examine the inodes? This is as close to "physically" as you're going to get, using Javascript.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •