简体   繁体   中英

how to execute the code on server side (php) each time the variable is incremented on the client side (java script)

I have a experiment which displays the random images from the database and the images are scrolled on the screen for 3 seconds, get paused for 3 seconds and scroll off the screen for 3 seconds and i'm maintaining an array with index "i" to store this images on client side and if the "i" value is incremented another image scrolls on to the screen, since i'm displaying the images from the database, if "i" is incremented another image should be displayed on to the screen from database (implies each time i is incremented the code on server side should be executed). can anyone tell me how to do this...

Here is the sample code,

//server side

$myQuery = "SELECT * from image WHERE img_id NOT IN (SELECT img_id from randomtrees where sid=".$sid.") ORDER BY rand() LIMIT 1";
$conn = mysql_connect("localhost","xxxxxx","xxxxxxxxxxxx");
mysql_select_db("database_name",$conn);
$result = mysql_query($myQuery);

$imagepath = 'path to the images folder which is in local host';
while ($row = mysql_fetch_array($result)) 
{ 
  $img = $imagepath.$row['img_name']; 
  $id = $row['imageid'];
  $img_id = $row['img_id'];
}
mysql_close($conn);

//client side

slideimages[i++] = '<img src="<?php echo $img ?>" id="<?php echo $id?>" name="r_img"/>' ;

If you care about speed of image loading time , retrieve them all first with php at once and store them in JS array .

Var X[]=<?php json_encode($imgs) ;?>;

If you care about page loading time , you can either get all images names and load them if necessarily with JS or making an Ajax request every time you need an image ( which will create a heavy load on the server but if you have large amount of data that storing them all in JS is a problem Or increase the file size then go for it ) .

Either:

1) Retrieve all the images you need in one SQL query, and write them into a JavaScript array, which your script can use to rotate the images client-side

2) Use JavaScript to refresh the page each time the images need to change by modifying window.location .

3) Use AJAX to make a request from JavaScript to the server to get another image, and use the response to change the image displayed on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM