How to scroll through an array of pictures with PHP and Javascript - php

I have a sql query that pulls an array that contains file paths to my images.
It is store in the variable $rows and I can access individual paths by indexing throught...
IE.
$rows[0]...$rows[n]
How can I utilize java script to step through this.
Final goal is for the picture to appear with a "Next" "Previous" button under it.
Hitting next would show the next image (without a refresh)
echo $rows[0];
would print
images/a.png

Maybe using PHP's json functions you can convert your PHP array to a js array... and then use javascript functions to control which picture to show
<script type="text/javascript">
var images = <?php echo json_encode($rows) ?>, counter = 0;
function prevImage() {
counter = (counter<=0)?images.length-1:counter-1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
function nextImage() {
counter = (counter==images.length-1)?0:counter+1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
</script>
and
<img src="img/0.jpg" id="myImage" />
Previous - Next​

Here is a little example to move your php array to a javascript array:
<?php
$row = array("image/image1","image/image2","image/image3");
?>
<html>
<head>
<title>Sample Array</title>
<script>
var jsArray = new Array();
<?php
for ($i=0; $i<3; $i++)
{
echo "jsArray[$i] = '$row[$i]';";
}
?>
for(i = 0; i < jsArray.length;i++)
{
alert(jsArray[i]);
}
</script>
</head>
<body>
<span>Sample Array</span>
</body>
</html>
Good luck!

Get your PHP array (server-side) to Javascript (clientside)
There are quite a few ways to go about doing this, but I'd recommend JSON. It has numerous advantages, but the most obvious one is you can store arrays and javascript objects as a string. If you're not familiar with it, this would be an excellent time to start including it in your workflow, considering you have to deal with Javascript.
PHP
Turn Array to JSON:
$jsonResults = json_encode($arrayOfResults);
Get JSON from PHP to Javascript:
<script>
var myAppsData = {};
myAppsData.slideshowJSON = JSON.parse($jsonResults);
</script>
Now your JSON object is accessible to Javascript at myAppsData.slideshowJSON.
The rest of the work is as simple as iterating through the object with a for loop (just like you would in PHP), grabbing the content and doing what you want with it.
Cheers!

Related

how to store php object to access its data on click with javascript

I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)

Creating jqplot graph in php page

Im trying to learn php by doing a little project using apache server. I have a php page where I want to display a bar chart with jqplot using data i pull from a MySql query. I already have a query working giving me the data i want. The problem is i dont know how to implement this into a jqplot graph. Im guessing i need to make an ajax call but if i can avoid that i would like to. my php page code so far is here http://snipt.org/oknnl2.
the javascript for the bar chart is here http://snipt.org/oknoi3.
i want the chart to render in div id=chartdiv thats on line 177. I have to visualize like 6 charts. if i can get some help on doing this one, im sure i can use the same process to build the others.
PHP cannot create the javascript plot and send it downstream to the client, but you don't have to make an actual AJAX call after the page is loaded either. Simple javascript once the page loads will suffice. If you retrieve the data you need at the PHP level, you can then make it available to javascript in the HTML received by the client. The steps to make this happen:
First, use PHP to retrieve the data you need from the MySQL database.
Then, output the plot data you retrieved using PHP inside a javascript
code block as part of the HTML that PHP sends to the client.
Execute the javascript with the data seeded by PHP on page load.
So, a simplified example:
<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
// append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
Hold on, javascript is loading the plot ...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
// we're combining the php array elements into a comma separated list
// so that when the code is output javascript thinks it's an array.
// if the $plot_row1 = array(1, 2, 3) then we'd get this:
//
// row1 = [1, 2, 3];
//
// if you needed quotes around the imploded php array values (if they
// are strings where javascript is concerned) you could do this instead:
//
// row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
// call your js function that creates the plot
showBrittleness(row1,row2,row3);
// add whatever js code you need to append the plot to $('#chartdiv')
}
</script>
UPDATE
According to a cursory examination of the jqplot docs, if you edit line 12 of the javascript you link from this:
var plot1 = $.jqplot('chart1', [s1, s2], {
To this:
var plot1 = $.jqplot('chartdiv', [s1, s2], {
Your function should render the plot in the 'chartdiv' id element. It seems the first argument to the $.jqplot function is the element in which to create it ...

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

How to make a simple dynamic slideshow/timelapse

I have a folder where are saved images from a webcam each X time.
I want to use these image to create a slideshow without transitions effects or music => i want to make a timelaps!
These slideshow must be dynamic (i can use php to build the list of image, each time a user want to watch the "video").
Any sugguestion and code to do this? Javascript? Php? or others??
Thanx!
That's the best way i found: simple and speedy
<HTML>
<HEAD>
<TITLE>Video</TITLE>
</HEAD>
<BODY BGCOLOR="#000000">
<img name="foto">
<SCRIPT LANGUAGE="JavaScript">
var Pic = new Array();
Pic[0] = '/images/image1.jpg'
Pic[1] = '/images/image2.jpg'
Pic[2] = '/images/image3.jpg'
//this part in real code is replaced with a PHP script that print image location dinamically
var t;
var j = 0;
var p = Pic.length;
var preLoad = new Array();
for (i = 0; i < p; i++) {
preLoad[i] = new Image();
preLoad[i].src = Pic[i];
}
//all images are loaded on client
index = 0;
function update(){
if (preLoad[index]!= null){
document.images['foto'].src = preLoad[index].src;
index++;
setTimeout(update, 1000);
}
}
update();
</script>
</BODY>
</HTML>
Have your PHP script send a meta refresh tag in the heading to reload the page with the latest image after the desired time.
NOTE: There are better, more AJAX-like ways of doing this, but this is the simplest. Using AJAX to reload just the image and not the whole page would be harder to write but a better user experience.

Export javascript when the script is using PHP variables

I've got 800 lines of JS code inside a php script for a site, and littered throughout some of the JS functions are some PHP echos to insert variables from PHP. I want as much of the JS out of the page as possible, but I don't know any good way to do so, as I'm not very expirenced in JS, and since I didn't write the code I don't even know the reason for 100% of this stuff.
Here's an example of one of the worst offenders and one I have no idea how I'd convert out of the PHP page.
function validateCostCenter(el){
var objCB = el;
var emp_code = objCB.name.substring(23,29);
var local_plant_ID ="<?=$plant['Plant']['LocationID']?>";
var cc_plants_array = ["<?=$cc_plants?>"];
var CCPlant=false;
var CostCenterExists=false;
var std_cs_array = [];
<?
$idx = 0;
foreach($employees as $emp){
foreach($std_cs as $cs){
if($emp['Emp']['id'] == $cs[0]['emp_id']){
echo "std_cs_array[".$idx."] = [\"".trim($emp['Emp']['code'])."\",\"".$cs['0']['emp_id']."\",\"".$cs['0']['locationid']."\",\"".$cs['0']['charge_back_plant_id']."\"];\n";
$idx++;
}
}
}
?>
Would the best way to do this be to remove all the pure JS functions from the page and include them as an external file, and just leave the partly-php ones 100% as is? This is one of the most wasteful and slow pages we have on our site so I'd like it to be as optimized as possible, and separate java script files makes everything easier to debug.
Add all these php-generated variables as parameters of your function:
function validateCostCenter(el, local_plan_ID, cc_plants_array, std_cs_array)
BTW you could use json_encode to export your $employers array to javascript.
I will illustrate possible approaches on a very simple example.
Approach 1: Computation in PHP
The page.php contains the computation and the generated Javascript file (as you have it now):
<body>
<?php
function sum_php($a) {
$sum = 0;
for ($i = 0; $i < count($a); ++$i) $sum += $a[$i];
return $sum;
}
$a = array(1, 2, 3);
$sum = sum_php($a);
?>
<script type="text/javascript">
// JS generated by PHP:
alert("sum_php=" + <?php echo $sum ?>);
</script>
</body>
Approach 2: Computation in Javascript
The computation is moved out of PHP into a separate Javascript file page.js. PHP supplies the variables to the JS functions by JSON-encoding:
(1) page.php:
<head>
<script type="text/javascript" src="page.js"> </script>
</head>
<body>
<?php
$a = array(1, 2, 3);
?>
<script type="text/javascript">
sum_js(<?php echo json_encode($a) ?>); // supply $a to JS function
</script>
</body>
(2) page.js:
function sum_js(a) {
var s = 0;
for (var i = 0; i < a.length; ++i) s += a[i];
alert("sum_js=" + s);
return s;
}
Assumiong that these values are non-cacheable....
If it were me, I'd have a PHP create a global object/array to hold the values, and generate non-cacheable javascript file, then move the rest of the code into a static, cacheable file, e.g.
user_vars.php:
<?php
session_start();
....get values for variables....
print "user_vars={";
print " ' plant': " . json_encode($plant) . "\n";
print " ', cc_plants_array: [" . $cc_plants . "]\n";
....etc
generic.js:
function validateCostCenter(el){
var objCB = el;
var emp_code = objCB.name.substring(23,29);
var local_plant_ID = user_var.Plant.LocationID;
var cc_plants_array = user_var.cc_plants_array;
.....
However unpicking what the generated values for each parameter will be can be a bit tricky - the simplest approach might be to write a temporary file as PHP generates the base HTML rather than try to create the data structures twice.

Categories