javascript slideshow array - php

I'm using slideshow 2 (http://www.electricprism.com/aeron/slideshow/) to show a couple of pictures on my website, the problem is number of images and their locations should be hard coded into the javascript code.
i want to use an array (from a php file output)
and somehow assign new values to the "var data" so that all of my images in the folder will be shown without the need to manually update each time.
any ideas?
<script>
window.addEvent('domready', function(){
var data = { '5.jpg': { caption: '1' }, '2.jpg': { caption: '2' }, '3.jpg': { caption: '3' }, '4.jpg': { caption: '4' }};
new Slideshow('overlap', data, { captions: { delay: 1000 }, delay: 3000, height: 300, hu: 'images/', width: 400 });
});
</script>

if you use PHP then you can easily do this.
say, you have logic that gets all your files into an array that looks like this:
$foo = Array("2.jpg" => "2", "3.jpg" => "3");
representing the filename and the caption
you can then do:
<?php echo json_encode($foo); ?>
to output it.
if you were to output it inside a js block into a variable:
var data = <?php echo json_encode($foo); ?>;
wich should actually render as:
var data = [{"2.jpg": "2"},{"3.jpg": "3"}];
Also, keep in mind in your example, you don't actually use an array, you use an Object. There's a substantial difference. In the output I suggest you will get an Array of Objects. You'd loop it like so:
Array.each(data, function(img) {
});
but because your keys are dynamic, it makes for difficult iteration, you need to Object.each or Object.keys or for (var key in obj) {} to get the properties. A better data structure would be:
$foo = Array(Array("name" => "2.jpg", "caption" => "two"), Array("name" => "3.jpg", "caption" => "three"));
which means in your js loop, you can reference:
Array.each(data, function(img) {
img.name; // filename
img.caption; // title
});

Related

Valid JSON, but can't display elements of array

I've been working on this for quite a while, and I've read TONS of posts on SO trying to figure out how I need to do this, and I can't seem to get it to work. I'm thinking it must be some aspect of the way I've coded things. So downvote away, but hopefully some kind soul will help me out.
I've tested using jsonlint, which comes back valid. I'm getting a response from the server with the values, I just can't seem to get anything in the browser other than when I just alert(response);. I need to be able to access the value of "cat_id_PK" and the other elements separately to loop through and display them in html table cells.
JSON:
{
"income": [
{
"cat_id_PK": 14,
"cat_name": "test1",
"cat_amount": "100.00"
},
{
"cat_id_PK": 15,
"cat_name": "test2",
"cat_amount": "200.00"
},
{
"cat_id_PK": 34,
"cat_name": "test3",
"cat_amount": "300.00"
},
"expense": [
{
"cat_id_PK": 14,
"cat_name": "tes41",
"cat_amount": "400.00"
},
{
"cat_id_PK": 15,
"cat_name": "test5",
"cat_amount": "500.00"
},
{
"cat_id_PK": 34,
"cat_name": "test6",
"cat_amount": "600.00"
}
]
}
PHP
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
JQUERY
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
});
"I've tested using jsonlint, which comes back valid."
No it doesn't, not for the JSON you've shown which has an error: it is missing a closing ] after the } and before the comma on the line before "expense" : .... But perhaps that's just a typo in your question given that you're generating the JSON with json_encode() (which wouldn't produce an error like that).
" I just can't seem to get anything in the browser other than when I just alert(response);"
So you are getting a value of some sort back then.
" but if I just alert response[0], it will return just the first character of the JSON array."
Yes, that's because response is a string - the raw string containing JSON, where what you want is to parse that string to get an object. Except that you don't have to do this manually because jQuery will do it automatically once you add dataType:"json" to your $.ajax() options.
"I actually was missing the datatype on this one, but even after adding it in, no matter what I try, I'm getting [Object:Object] or undefined. I'm literally doing nothing more than alert(response);"
Once you add the dataType:"json" the response parameter will be an object, which when you try to alert will correctly display as [object Object]. If you use console.log(response) then in your browser's console you'd see the actual object. You'd get undefined if you try to access a property that doesn't exist.
"I need to be able to access the value of cat_id_PK and the other elements separately to loop through and display them in html table cells."
Your response object has two properties, income and expenses, both of which are arrays of object. So use response.income to access the first array of objects, and response.expenses to access the second array of objects. The first income item is response.income[0] and the property you asked about is response.income[0].cat_id_PK. So you can use a for loop, or use $.each() to iterate over the array and do something with each .cat_id_PK property:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "json",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
var tr = $("<tr></tr>");
// using traditional for loop for income items
for(var i = 0; i < response.income.length; i++) {
$("<td></td>").text(response.income[i].cat_id_PK).appendTo(tr);
}
tr.appendTo("#idOfTableHere");
var tr = $("<tr></tr>");
// use equivalent jQuery $.each for expense items
$.each(response.expenses, function(i, v) {
$("<td></td>").text(v.cat_id_PK).appendTo(tr);
});
tr.appendTo("#idOfTableHere");
});
The code I've shown creates new td elements in each loop, appending them to new table rows, and then after each loop the new row is appended to a table that I've assumed already exists on your page with id="idOfTableHere".
try this you miss dataType:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: "display_categories", cur_month:cur_month},
dataType:"json",
});
request.done(function(response){
//for each element put values in <td></td> tags.
});

FullCalendar JSON Feed not working: my calendar doesn't put the data from the JSON feed onto my webpage

Why doesn't my calendar put the data from the JSON feed onto my webpage?
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
events: 'myfeed.php',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
eventSources: [
// your event source
{
url: '/myfeed.php', // use the `url` property
color: 'red', // an option!
textColor: 'black' // an option!
}
// any other sources...
],
eventClick: function(calEvent, jsEvent, view) {
if (!confirm("Are you sure you want to delete this?")) {
}
else
{
// remove calender, and post the info to page
$.post("mybook.php", { idnumber: calEvent.id, remove: '1' } );
$('#calendar').fullCalendar('removeEvents', [calEvent.id]);
}
}
});
});
</script>
JSON Feed PHP Code
<?php $arr = array('id' => '1', 'title' => 'Apples', 'start' => '1372530615', 'end' => '1372537615', 'allDay' => false);
echo json_encode($arr);
?>
Charles web debugger shows that the script is assessing the right page, and it has a response. But, my calendar does nothing. :( I thought it might be because I was using SSL, but I have tried both ways.
Reduced my code to
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<script type='text/javascript' src='fullcalendar.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
events: 'myfeed.php'
});
});
</script>
JSON Feed Output
{"id":"1","title":"Apples","allDay":false,"start":"1372507615","end":"1372537615"}
Remove eventSources if you are already using events property.
Had to put [ ] around my JSON Output.
I want to confirm the accepted answer above. I have seen several such questions about events not showing up in FullCalendar, particularly JSON, and the solutions seem to be about syntax. You have to give FullCalendar EXACTLY what it wants to see, and documentation on that point is somewhat unclear. Expect a lot of trial and error.
I landed on this question with the same issue and did the following things to get it to work:
Make sure that there are square brackets [] at the end
Make sure that there are no extra commas at the end (this is what got me) - apparently it is ok with it when using a the paramenters inline, but when loading from JSON it has this issue
Use double quotes for both fiend and values.
I ended up rewriting my php to create an object array, load the values into the array, and then convert it into JSON (this took care of all the above JSON formatting issues)
My JSON output looked like:
[{"title":"Vishal","start":"2018-01-12 00:00:00","end":"2018-01-12 10:00:00"},{"title":"Vishal","start":"2018-01-14 14:00:00","end":"2018-01-14 15:00:00"}]
My PHP code looks like:
$data = array();
foreach($results as $run)
{
$obj = (object) [
'title' => $run->firstname,
'start' => $run->startdatetime,
'end' => $run->enddatetime
];
$data[] = $obj;
}
echo json_encode($data);
I hope this helps.

Passing array values from php to javascript data returns only one value

This function works fine, but it only returns one value. What I'm missing here?
Here's my code:
<script type='text/javascript'>
$(function () {
<?php
//Get the names and id's
$get_info=mysql_query("select * from table where id = '1'");
if($get_info){
while($row_info=mysql_fetch_array($get_info))
{
$username=$row_info['name'];
$user_id=$row_info['profile_id'];
?>
onDataRequest:function (mode, query, callback) {
var data = [
{ id:<?php echo $user_id;?>, name:'<?php echo $username;?>', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' }
];
data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
}
});
<?php
}}
?>
});
</script>
Expected result:
{
id: 295,
name: 'Mike',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
},
{
id: 296,
name: 'John',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
}
Actual output:
{
id: 295,
name: 'Mike',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
}
It just returns 1 item.
You database fetch loop isn't preserving each fetched value. You simply overwrite the previous fetch call with the current fetch. perhaps you meant something like this:
while ($row_info = mysql_fetch_asssoc($result)) {
$username[] = $row_info['name'];
$user_id[] = $row_info['profile_id'];
}
The [] notation on the vars tells PHP to treat the vars as array and push the new values into the array.
You'd then insert the arrays into javascript with:
var usernames = <?php echo json_encode($username); ?>;
var user_ids = <?php echo json_encode($user_id); ?>;
Every time you loop, you are assigning new values for your onDataRequest javascript function, however, it's the same function every time. You should think about execution order - first, you do PHP&MySQL server-side and what is generated as HTML or Javascript code there gets rendered and/or executed client-side later.
Basically, you have a PHP loop that goes over a set of values and those values are put inside a Javascript code that is within a HTML code block. So whatever you fetch from your database server last, is what is actually executed client-side.
The main idea here is that you shouldn't mix your server-side PHP code with client-side HTML or Javascript code.

Get value with php and mysql in var name[value1,value2,value2]

How I can insert array value in php and mysql from variable Var s1, s2, s3:
$(function () {
var s1 = [100, 200, 300]; //How to Get Value from mysql database
var s2 = [30, 80, 90]; //How to Get Value from mysql database
var s3 = [120, 90, 80]; //How to Get Value from mysql database
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['2010', '2011', '2012'];
var plot1 = $.jqplot('chart3', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
shadow: true, // show shadow or not.
renderer: $.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true
}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{label: 'Hotel'},
{label: 'Event Regristration'},
{label: 'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {
formatString: '$%d'
}
}
},
grid: {
borderColor: '#000', // CSS color spec for border around grid.
borderWidth: 2.0, // pixel width of border around grid.
shadow: true // draw a shadow for grid.
}
});
// Bind a listener to the "jqplotDataClick" event. Here, simply change
// the text of the info3 element to show what series and ponit were
// clicked along with the data for that point.
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
});
});
2 ways:
Ajax
Use: $.getJSON ( http://api.jquery.com/jQuery.getJSON/ )
var ses = {};
$.getJSON('page_adress.php', {variable_you_want_to_pass1: 'its value', variable_you_want_to_pass2: 'var 2 value'}, function(data) {
ses = data;
});
In your PHP:
<?php
$passed_var_1 = $_REQUEST['variable_you_want_to_pass1'];
//.... etc
//Here you get your data from mysql, cast it into array
header('Content-type: application/json');
echo json_encode($dbdata);
?>
So basically after request finishes you will have exact array you had in PHP transferred in JavaScript. Have in mind that this technique uses AJAX. If you want to avoid that, you will have to use second technique.
Dynamically Creating JS
Make PHP generate your javascript. In this case you would have in your main page
<script src="js_data.js.php" type="text/javascript"></script>
In your js_data.js.php file:
<?php
header("content-type: application/x-javascript");
$s1 = array(100,200,300);
//....
var s1 = [<?=implode(', ', $s1)?>],
s2 = [<?=implode(', ', $s2)?>],
s3 = [<?=implode(', ', $s3)?>];
?>
First method (w/o ajax & json)(untidy-way)
First fetch the value from database and have it in PHP variable.
Then put html element in page and assign the value to it.
Then use it in javascript using document.getElement method.
// assume that you have got value from database in $valueFrmDB.
$valueFrmDB;
Now, take html element(you might have to take more than one)
<input type="hidden" id="something" name="something" value="echo value of $valueFrmDB here" />;
Then, in javascript
var vfd = document.getElementById('something').value;
convert string to array
Second method(with ajax and json)(simple & correct but must know ajax and json)
Use ajax to fetch the values from database
Then use json to pass that values to javascript
simply you can do this by:
<?php
$query = mysql_query("SELECT * FROM attendence");
$results = array(array());
while($line = mysql_fetch_array($query)){
$results[] = $line;
}
?>
Javascript
<script type="text/javascript">
$(document).ready(function(){
var data = <?php echo json_encode($results); ?>; //array uses here
var plot1 = jQuery.jqplot ('chart1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true}
},
legend: { show:true, location: 'e' }
});
});
</script>

Creating an associative array from PHP through AJAX in JQUERY

My first cry for help here.
Not sure if my title is properly explicit but it's the only one I can come up with right now. I've been at it for 2 days now and I have read so many different things that I think I am getting completely confused. I'll try to be as precise as possible.
Here's my problem,
First, this is the jQuery code I am basing this on:
$thumbnails.find( 'a' ).each( function() {
pictures.push({
src: $( this ).attr( 'href' ),
title: $( this ).find( 'img' ).attr( 'title' ),
valign: $( this ).find( 'img' ).data( 'valign' )
});
})
You notice the pictures.push in there.
Now, this goes with,
$.vegas( 'slideshow', {
backgrounds: pictures,
delay: 4000,
fade:5000
})( 'overlay' );
Note how the background attribute uses pictures to get the images' names it needs. I'm not sure now how to call pictures. Is it an associative array or is it an object?
Anyhow, I don't want to get the images' filenames from the HTML nodes. I am using PHP to fetch filenames in directories on the server and generate an XML document with those filenames.
Here is the part that generates the XML document in my PHP script, (I only need 5 images for my need)
header("Content-type: text/xml");
echo '<?xml version="1.0"?>';
echo "<img>";
for($i=0;$i<5;$i++){
echo "<src>img/" . $rep_aleatoire[$i] . "/" . $img_aleatoire[$i] . "</src>";
echo "<title>" . $img_aleatoire[$i] . "</title>";
}
echo "</img>";
And this is what thes XML document looks like,
<img>
<src>img/portraits/DSC_0161.jpg</src>
<title>DSC_0161.jpg</title>
<src>img/nature/DSC_0019 copy-tych 3.jpg</src>
<title>DSC_0019 copy-tych 3.jpg</title>
<src>img/portraits/DSC_0157.jpg</src>
<title>DSC_0157.jpg</title>
<src>img/editions/DSC_0053.jpg</src>
<title>DSC_0053.jpg</title>
<src>img/editions/DSC_Ant.jpg</src>
<title>DSC_Ant.jpg</title>
</img>
And here is the JQUERY part I use to get that XML data,
$.get("main.php", function(data){
var rep = new Array;
var file = new Array;
$(data).find("img").each(function(){
$(this).find('src').each(function(i){
rep[i] = $(this).text();
});
$(this).find('title').each(function(i){
file[i] = $(this).text();
});;
for(i=0;i<rep.length;i++){
pictures.push({
src: $(rep[i]),
title: $(file[i])
});
}
});
});
pictures has been initialized out of the scope of this function so it should be available anywhere I need it but it is not. If I try to access it outside that function, it is empty.
Also, when within the scope of that function, all it contains is objects. I don't even know if I'm doing it the proper way. I have tried so many different ways I can't even remember. I just can't get the actual data generated in the XML document.
I sure hope I have been clear enough and you guys understand what I am after.
I simply want to generate the proper format of pictures so it is usable in the $vegas function.
Any help will be greatly appreciated.
First of all. Always declare your variables.
Wrong declaration:
var rep = new Array;
var file = new Array;
Should be either
var rep = new Array();
var file = new Array();
Or even better:
var rep = [];
var file = [];
Declare i, you was using in the last loop.
for(var i=0;i<rep.length;i++){
...
Or even better:
var i;
for(var i=0;i<rep.length;i++){
..
When you done with that you'll notice that you trying to access jquery objects by your array value.
pictures.push({
src: $(rep[i]),
title: $(file[i])
});
And you probably meant:
pictures.push({
src: rep[i],
title: rep[i]
});
Of course, make sure that var pictures available in all scopes, where you are using it.

Categories