0

I've been searching for a way to take the user to a random page when they press a button with JavaScript/jQuery. Everything I've seen has all the pages in an array, and then uses a script to randomly choose an index.

Would it be possible to do something like this without adding all the pages into an array. I don't want to sit there and add every page/image in the directory to a large array and then have the script run, I just want it to go through the appache directory list and grab something by itself.

Can this be done? I know we're supposed to include code we have so far, but this is more of a conceptual question.

  • Yes it's possible, but you have to get the url's from somewhere. What's that "apache directory list"? – rupps Mar 31 '14 at 21:14
  • [JavaScript: List Directory Contents With Apache Indexes](http://theo.cc/blog/2012/11/javascript-list-directory-contents-with-apache-indexes/) || [Get file names of Apache Directory Listing](http://stackoverflow.com/a/13670594/2033671) –  Mar 31 '14 at 21:24

3 Answers3

3

Use ajax to get your link:

$.ajax({
    method: "GET",
    url: "/getRandomLink", // I don't know which server side language you're using, I presume its PHP
    dataType: "text", // text will be enought if it only returns a link
    success: function(link) {
        window.location.href = link;
    }
});

Then put this inside an event of your choice. Nice and easy.

UPDATE

The return of your service must be a string with the link. I'm suposing you're using PHP, so will be something like:

<?php

    $randomLink = "";// Code to get the random link here

    echo $randomLink; // e.g.: http://www.google.com/

?>
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
1

Something needs to provide the list of files for your script to randomly choose from. That's going to be either a pregenerated array or an ajax request.

These would work:

...but for your purposes it would make more sense for your server side script to just return a single randomly selected file, instead of using bandwidth for the whole list only for the client to discard all but one.

Community
  • 1
  • 1
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
0

Edit to reflect the comment given by the OP. Pardon the jQuery.

Assuming the directory index you've got is a standard Apache Auto-Index page:

//jQuery doc.ready, because I'm too lazy to do something better ;)
$(function () {

    var links = [];

    $.ajax(
        {
            //url: location.pathname, // Use current page
            url: '/directoryname/', //directory index of your choice
            success: saveAjaxedLinks
        }
    );


    function saveAjaxedLinks (data, e) {
        // Scrape anchors off of page. 
        // Note -- there might be other anchors on the page 
        // that you don't want to pick up, say the "up a directory level" anchors.
        // you can filter those out if you want, but you'll have to determine the criteria for doing so.
        var directory = $('a', data);

        //Get anchor nodes and store them.
        links = directory.get();

        //Assign event listener to button after the data is ready.
        $('button#yourbuttonid').on( 'click', onclickGetRandomPage );

        //uncomment to do action immediately.
        //onclickGetRandomPage();
    }

    function onclickGetRandomPage (e) {
        if ( !!e && !!e.preventDefault )  {
            e.preventDefault();
        }
        //if no links on the index, do nothing.
        if ( !links.length ) return;

        //Get the a random index from the links.
        var rnd = Math.floor( Math.random()*links.length);

        for (var i = 0, len = links.length; i < len; i++ ) {

            // Make sure there's an actual href inside the random link. 
            // Also, check to make sure the links arent just hashes. Not necessary if you're just using an apache auto-index.
            // If there are certain types of links you don't want (eg. directory roots), you can filter them out here.
            if ( !!links[rnd].href && links[rnd].href.replace( links[rnd].hash, '' ) !== (location.href.replace( location.hash, '' ) ) ) { 
                //console.log(links[rnd].href); //Log out the links if you're just testing
                window.location.href = links[rnd].href;
                break;
            } else {
                //That link was no good, get a different one.
                rnd = Math.floor( Math.random()*links.length );
            }
        }
    }


});
Keegan Brown
  • 515
  • 3
  • 5
  • I may have not been clear in my original post. Say for example you go to a directory on a web server and it has a directory listing. You choose one of the html pages on the directory listing and you're presented with a button that says "next". That's what I have, and when you click next, I want it to take the user to a random page. The listing is on the page itself that has the button. – Joshua Potter Mar 31 '14 at 22:42
  • Ok, assuming that you want to use the directory listing as your source for URLs (from which to choose a random link), you can use ajax to pull in that page, and pick a random link from that page, using a similar function to what I had before. I'll mod my code to show you what I mean. – Keegan Brown Apr 01 '14 at 14:17
  • I was getting an error for `.on( click, onclickGetRandomPage );` saying "click is undefined" so I switched to to `.click` and now it works perfectly. Thank you so much for your assistance and the detailed comments, the code is very easy to understand, which is something I was hoping from a comment: to actually understand what's going on. Once again, thanks! – Joshua Potter Apr 01 '14 at 19:47
  • Glad to help! Sorry about the on statement -- the word 'click' should be in quotes. I cleared up that typo in my example. – Keegan Brown Apr 02 '14 at 13:43