0

I am trying to create an HTML button that when clicked:

  • Selects a random URL from an API
  • Redirects to that selected URL

I have tried using an Array but as the list expands it no longer is efficient.

The code I have been using is a simple one:

<script type="text/javascript">
    var urls = [
"/product/245170",
'/product/245166',
'/product/245189',
'/product/245108',
'/product/245041',
'/product/245098',
    ];

    function discoverItems() {
        var url = urls[Math.floor(Math.random()*urls.length)];
        window.location = url; // redirect
    }
</script>

I want it now to search from xyp.com/api/products and ask it to select a random url from there.

Help please!

CR_01
  • 1
  • 1
  • [lmgtfy](http://www.w3schools.com/xml/ajax_intro.asp) – I wrestled a bear once. Oct 20 '16 at 12:17
  • @Pamblam the TP wants to redirect, not just sending an ajax request – messerbill Oct 20 '16 at 12:19
  • but i dont get what you want to achieve...`I want it now to search from xyp.com/api/products and ask it to select a random url from there.` what do you mean? – messerbill Oct 20 '16 at 12:20
  • messerbill.. seems to me like he wants to poll that url, which presumably provides a list of urls, and choose one of them at random. this task requires ajax. – I wrestled a bear once. Oct 20 '16 at 12:23
  • The list of urls should be populated in your backend, and the list should be part of the page source. The same task is not possible to be done with AJAX if you want to access another server. [Cross domain requests are not allowed](http://stackoverflow.com/a/1201459/3652270). It can be done with AJAX only if you want to do it within the same server. – sanastasiadis Oct 20 '16 at 14:41

0 Answers0