title: Use jquery / ajax to run small php script
body: <p>I am trying to give a div a random background image. I have a very simple bit of php in the head of my page.</p>
  
  <pre><code>&lt;?php 
  $bg = rand(1, 6); 
  $bgchange = $bg.".jpg"; 
  ?&gt;
  </code></pre>
  
  <p>followed by </p>
  
  <pre><code>&lt;style type="text/css"&gt;
  .cover {
  background-image: url('../img/backgrounds/&lt;?php echo $bgchange; ?&gt;');
  }
  &lt;/style&gt;
  </code></pre>
  
  <p>This is working but sometimes fails for some reason especially on a poor internet connection.</p>
  
  <p>What I want to do is use jquery so that on document ready AJAX points to the php file (the php i currently have in the header), I am hoping this will make the php more reliable as it is not trying to load the image until after the document is ready. </p>
  
  <p>I've been told 
  You can detect the "document-ready" event with a Javascript script and when that is triggered, perform an AJAX request to a PHP page that will run the script you need.</p>
  
  <p>With jQuery it gets as simple as using ready() and ajax().</p>
  
  <p>Can anyone suggest how to implement this as I cant find anyone who has already done this anywhere...</p>
  
  <p>The solution i used is:</p>
  
  <pre><code>var images = [
  '1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg'];
  
  var randomNumber = Math.floor(Math.random() * images.length);
  var randomImage = "images/" + randomNumber + ".jpg";
  jQuery.ajax(randomImage);
  
  $(document).ajaxComplete(function() {
  $('.cover').css({ 'background-image': 'url(' + randomImage + ')' }).addClass('loaded');
  })
  </code></pre>
  
  <p>and the CSS</p>
  
  <pre><code>body, html {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  }
  
  .cover {
  height: 100%; width: 100%;
  margin: 0 auto;
  background: #bada55;
  background-position: 50% 50%;
  transition: opacity 2s ease;
  opacity: 0;
  }
  
  .loaded {
  opacity: 1;
  }
  </code></pre>
  
  <p>only one of the background images is downloaded and then to be able to perform a function such as a subtle fade in only when that image has loaded etc.</p>