Question

Here is the code that I am currently using... (javascript injection)


Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
var imgList = [
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',   'img/1.jpg',
  'img/1.jpg',  'img/1.jpg'   // Note: No comma after last entry
];

function showImage() {
  var today = new Date();
  var weekno = today.getWeek();
  document.getElementById('WeeklyImage').src = imgList[weekno];
  document.getElementById('WeeklyImage').alt = imgList[weekno];
//  alert(weekno+'\t'+imgList[weekno]);
}

I was wondering if someone can tell me how I convert the image src to a php variable like $weeklyImage or something like that so I can do the following...


echo "<img src='" . $weeklyImage . "'>";

I need the output to be in PHP so that I can use the variable for other areas of the site that require PHP functions.

If not possible, any other suggestions would be appreciated.

Thanks!

Was it helpful?

Solution

It is impossible to directly pass values from JavaScript to PHP, because PHP runs on your server, then the result of your PHP script is sent to the client, and only then is JavaScript even run.

For your problem, there is absolutely no need to use JavaScript at all. You can get the current week with date('W') and similarly store the entire list of images in a simple array:

$images = ['image1.jpg', 'image2.jpg'...];
echo '<img src="'.$images[date('W')].'">';

OTHER TIPS

You Just Cannot assign javascript variable value to a PHP variable just because

  1. PHP is a Scripting Language
  2. Php runs before javascript.
  3. Thus the reverse is possible i.e. php variable can be assigned to a javascript variable.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top