API: Random Item

I've got a theme that uses ajax to swap content on the homepage. I'm looking for an efficient way to fetch a RANDOM item via Javascript.

Right now, I'm just selecting something random from the first 50 results and returning an ID, like so...

function fetch_random_id(){

     jQuery.get( "/api/items?featured=true&public=true", function( fi, fs ) {
	if(fs === 'success'){

          rand=Math.floor(Math.random() * (50 - 0) + 0);

          return fi[rand].id;


          return false;




Is there a method by which I can use the API to fetch a truly random item?

[the site in question]

Thanks, Erin

The API itself doesn't let you ask for a random item. You could probably figure something close out in a roundabout way, though.

If you do one query with per_page=1, and then look at the response header's Link rel="last", you could parse out the total number of items available via the API.

The link would look something like

<http://localhost/Omeka/api/items?per_page=1&page=1937>; rel="last",

Then have your javascript pick a random number less than the number of pages that gives you, and ask for that page. So, if the random number the js gives you is 123, query


Not entirely pretty, but would do the job, I think. After that first query you could just store the total number in JS somewhere so you don't have to repeat the two-part process.

Of course, that's assuming you need that to happen dynamically, without a page reload. If it's just a one-shot deal, that's better done via the PHP and querying for a random item directly from the table.

Thanks for the tips! I ended up grabbing the Omeka-Total-Results number from the response header and using that to create the new query using your method for getting a random item.

var total = xhr.getResponseHeader("Omeka-Total-Results");
var r=Math.floor(Math.random() * (total - 0) + 0);
var query="/api/items?per_page=1&page="+r;

Cheers -- E

AH! I completely forgot about the total results. yeah, that's much better than all the extra parsing!