1

This is the code I have so far, which at the moment loads the info from the xml file as desired with javascript. I've set it to loop 4 times to select 4 images, but these are obviously just the first 4 from the xml file.

Does anyone know the best way to make it randomly select 4 none repeated images from the xml file.

<script>
if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","include/photoLibrary.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("photo");
    for (i=0; i<4; i++)
    { 
    document.write('<a href="');
    document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
    document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
    document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
    document.write('"><img src="');
    document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
    document.write('" alt"');
    document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
    document.write('"/></a>');                      
    }
</script>

If it helps in any way, this is an example of the xml, you'll see there is an attribute to photo which gives it a unique id.

<gallery>

<photo id="p0001">
<title>Pergola</title>
<path>photos/Pergola.jpg</path>
<thumb>photos/thumbs/Pergola.jpg</thumb>
<description>Please write something here!</description>
<date>
    <day>04</day>
    <month>04</month>
    <year>2006</year>
</date>
</photo>

</gallery>

I'm willing to use php as an alternate to javascript.

Turner855
  • 13
  • 3
  • Is using PHP a possiblity? – Coder404 Feb 02 '13 at 23:26
  • It can be I suppose if need be, was just trying to keep it simple using javascript. But if it is going to be easier to implement and more effective then why not. – Turner855 Feb 02 '13 at 23:33
  • Javascript does not have IO abilities so you cannot parse XML in js – Coder404 Feb 02 '13 at 23:36
  • Any suggestions as to how to go about it in php? – Turner855 Feb 02 '13 at 23:40
  • i believe use of AJAX could overcome the "PHP need" for just getting the file from somewhere.. also you could use a filter function along with Math.rand to do that "random image non repeated image", i don't see the where PHP is needed.. – Gntem Feb 02 '13 at 23:44
  • @Turner855 I have posted how to parse in PHP – Coder404 Feb 02 '13 at 23:50
  • Thanks will have a look. – Turner855 Feb 03 '13 at 00:00
  • @Coder404: What on earth makes you say that you can't parse XML in JS? JS is often used to manipulate/interact with the DOM... That same DOM-API has to be able to parse markup: [here's an example](http://jsfiddle.net/d6cgf/1/) – Elias Van Ootegem Feb 03 '13 at 00:16
  • @EliasVanOotegem I was always taught that JS did not have IO Capabilities – Coder404 Feb 03 '13 at 00:17
  • @Coder404: JS, left to its own devices doesn't have IO capabilities, but the DOM API, and the engine on which JS runs do... there is no `echo` function, but a `document.write(ln)` ==> sending a string to the DOM, and asking it to output some data _is_ possible – Elias Van Ootegem Feb 03 '13 at 00:22
  • @Coder404 its worth noting that the JS spec does not include IO for an good reason. Not including IO makes the JS language flexible and effective as a multipurpose language. Host environment must provide an API for preforming IO and/or other tasks. This allows environments like node.js and chrome to share the same VM, V8, and provide a completely different API. The JS specification is maintained by ECMA. DOM API however belongs to the W3C. The DOM API, unfortunately is the reason is why many people feel they dislike JS. They assume wrongly the poorly designed API it is part of the JS language. – Robert Hurst Feb 03 '13 at 12:12

4 Answers4

3

You could just add

x = Array.prototype.slice.call(x).sort( function () {
    return Math.random() > 0.5 ? 1 : -1 
} );

straight after

var x = xmlDoc.getElementsByTagName("photo");

This would create a randomly ordered array of the elements, the first four of which would be iterated by the for loop.

Edit

Note that this method will not produce a properly random shuffle of an array, see Is it correct to use JavaScript Array.sort() method for shuffling?, and I do not recommend it.

Community
  • 1
  • 1
MikeM
  • 13,156
  • 2
  • 34
  • 47
  • That works almost perfectly, just occasionally get a repeated image. – Turner855 Feb 02 '13 at 23:59
  • @Turner855. So the same image may appear twice in the nodeList? BTW, the call to slice won't work in IE<9, so if that is a problem you would have to create the array with a loop before sorting. – MikeM Feb 03 '13 at 00:05
2

First things first. Try not to use document.write as this method acts inconstantly when the DOM is ready vs when it is still initializing. Its considered a bad practice.

I also recommend using functions to break down the complexity of your code and make it more readable.

You should be aware that XHR objects are not synchronous. You need to wait for the xml data to be retrieved via the readystatechange event.

Lastly you don't have to build strings of html in the browser. The DOM API allows you to create the anchor and image tags as proper nodes which can be attached to the DOM tree.

Hope that helps.

(function() {

    //fetch the gallery photos
    getXML('include/photoLibrary.xml', function(xml) {
        var photos, pI, photo, anchor, image, anchors = [];

        //pick four photos at random
        photos = getRandom(makeArray(xml.getElementsByTagName('photo')), 4);

        //build out each photo thumb
        for(pI = 0; pI < photos.length; pI += 1) {
            photo = photos[pI];

            //create the anchor
            anchor = document.createElement('a');
            anchor.setAttribute('href', photo.getElementsByTagName('path')[0].childNodes[0].nodeValue);
            anchor.setAttribute('class', 'lytebox');
            anchor.setAttribute('data-lyte-options', 'group:vacation');
            anchor.setAttribute('data-title', photo.getElementsByTagName('description')[0].childNodes[0].nodeValue);

            //create the image
            image = document.createElement('img');
            image.setAttribute('src', photo.getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
            image.setAttribute('alt', photo.getElementsByTagName('title')[0].childNodes[0].nodeValue);

            //insert the image into the anchor
            anchor.appendChild(image);

            //insert the anchor into the body (change this to place the anchors else were)
            anchors.push(anchor);
        }

        //when the DOM is loaded insert each photo thumb
        bind(window, 'load', function() {
            var aI;

            for(aI = 0; aI < anchors.length; aI += 1) {
                //replace document.body with whatever container you wish to use
                document.body.appendChild(anchors[aI]);
            }
        });
    });

    /**
     * Fetches an xml document via HTTP method GET. Fires a callback when the xml data
     * Arrives.
     */
    function getXML(url, callback) {
        var xhr;

        if(window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            throw new Error('Browser does not support XML HTTP Requests.');
        }

        //attach the ready state hander and send the request
        xhr.onreadystatechange = readyStateHandler;
        xhr.open("GET","photos.xml",false);
        xhr.send();

        function readyStateHandler() {

            //exit on all states except for 4 (complete)
            if(xhr.readyState !== 4) { return; }

            //fire the callback passing the response xml data
            callback(xhr.responseXML);
        }
    }

    /**
     * Takes array likes (node lists and arguments objects) and converts them
     * into proper arrays.
     */
    function makeArray(arrayLike) {
        return Array.prototype.slice.apply(arrayLike);
    }

    /**
     * Extracts a given number of items from an array at random.
     * Does not modify the orignal array.
     */
    function getRandom(array, count) {
        var index, randoms = [];

        //clone the original array to prevent side effects
        array = [].concat(array);

        //pull random items until the count is satisfied
        while(randoms.length < count) {
            index = Math.round(Math.random() * (array.length - 1));
            randoms.push(array.splice(index, 1)[0]);
        }

        return randoms;
    }

    function bind(element, eventName, callback) {
        if(typeof element.addEventListener === 'function') {
            return element.addEventListener(eventName, callback, false);
        } else if(typeof element.attachEvent === 'function') {
            return element.attachEvent('on' + eventName, callback);
        }
    }
})();

Edit: Fixed three errors. The DOM needs to be loaded before inserting the nodes. XML nodes don't have innerHTML property. Array.concat does not see DOM NodeList objects as Arrays.

Robert Hurst
  • 8,902
  • 5
  • 42
  • 66
  • Thanks for the tips, you're right makes it much more sense. Just quickly tried and copied and pasted to my site, but it displays nothing. I assume it still sits in my – Turner855 Feb 03 '13 at 01:18
  • I'm getting an error with the following TypeError: photo.getElementsByTagName is not a function [Break On This Error] anchor.setAttribute('href', photo.getElementsByTagName('path')[0].innerHTML); – Turner855 Feb 03 '13 at 01:57
  • Thank you, that's fantastic! Works now with no problems at all. :) – Turner855 Feb 03 '13 at 16:45
0

In PHP this is how you parse a file:

index.php

<?php
$doc = new DOMDocument();
  $doc->load( 'book.xml' );

  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;

  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;

  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;

  echo "$title - $author - $publisher\n";
  }?>

book.xml

<books>
  <book>
  <author>Jack Herrington</author>
  <title>PHP Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  </books>
Coder404
  • 742
  • 2
  • 7
  • 21
0

in php you pick random something like this

<?php

$xml_string = 
'<gallery>
<photo id="p0001">
<title>t1</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0002">
<title>t2</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0003">
<title>t3</title>
<path>photos/Pergola.jpg</path>
</photo>
</gallery>';

$xml  = simplexml_load_string($xml_string);
$arr = (array) $xml;
shuffle($arr['photo']);
for($i =0; $i < 2; $i++){
  $picture = array_pop($arr['photo']);
  print_r($picture);
}
rana
  • 81
  • 4