I applied an ajax pagination in my web project it worked well however my flowplayer plug-in stopped working i think they are in conflict or they are overwriting each other's javascript so i ve searched for a while in web but i couldn t find the solution. ( i tried even noConflict method)
What should i do ? Can anyone help me please ?
Here is my index.php:
<?php
// This first query is just to get the total count of rows
$sql = "SELECT id_video FROM video ORDER BY id_video DESC";
$res = $connexion->query($sql);
$count=$res->rowCount();
//print_r($count);
// Here we have the total row count
//$total_rows = $row[0];
// Specify how many results per page
$rpp = 4;
// This tells us the page number of our last page
$last = ceil($count/$rpp);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Exemple</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/typocolor.css" />
<link rel="stylesheet" href="css/index_media_ie.css" />
<link rel="shortcut icon" href="image/favicon.ico" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600&subset=latin,latin-ext,cyrillic-ext' rel='stylesheet' type='text/css'>
<script>
$(document).ready(function()
{
flowplayer(".player", "./flowplayer/flowplayer-3.2.16.swf",{
clip: {
autoPlay: false,
autoBuffering: false
}
});
});
</script>
<script type="text/javascript" >
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
function request_page(pn){
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
var hr = new XMLHttpRequest();
hr.open("POST", "pagination_parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "<li>";
html_output += "<article>";
html_output += "<h3>"+itemArray[0]+"</h3>";
html_output += "<a class=\"player\" href="+itemArray[1]+" style=\"border:1px solid #bfbfbf;display:block;width:90%;height:250px;position:relative;margin:auto;padding:5px;background-color:white;box-shadow: 0px 0px 5px rgb(204, 204, 204);\"></a>";
html_output += "<p>"+itemArray[2]+"</p>";
html_output += "</article>";
html_output += "</li>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
// Change the pagination controls
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
</head>
<body>
<div id="wrapper">
.
.
.
</div>
<script src="./js/jquery.js"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
<!-- bxSlider Javascript file -->
<script src="./js/bxslider/jquery.bxslider.min.js"></script>
<!-- bxSlider CSS file -->
<link href="./js/bxslider/jquery.bxslider.css" rel="stylesheet" />
<script src="./flowplayer/flowplayer-3.2.12.min.js"></script>
<script src="./js/comportement.js"></script>
<script> request_page(1); </script>
</body>
</html>
and pagination_parser.php (which i found it on developphp.com)
<?php
// Make the script run only if there is a page number posted to this script
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9]#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9]#', '', $_POST['last']);
$pn = preg_replace('#[^0-9]#', '', $_POST['pn']);
// This makes sure the page number isn't below 1, or more than our $last page
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last) {
$pn = $last;
}
// Connect to our database here
include_once("bdd.php");
$connexion->exec("SET CHARACTER SET utf8");
// This sets the range of rows to query for the chosen $pn
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT * FROM video ORDER BY id_video DESC $limit";
$res = $connexion->query($sql);
//$query = mysqli_query($db_conx, $sql);
$dataString = '';
while($row = $res->fetch(PDO::FETCH_ASSOC))//mysqli_fetch_array($query, MYSQLI_ASSOC)){
{
$titre=$row['titre'];
$description=$row['description'];
$src=$row['source_video'];
//$itemdate = strftime("%b %d, %Y", strtotime($row["datemade"]));
$dataString .= $titre.'|'.$src.'|'.$description.'||';
}
// Close your database connection
//mysqli_close($db_conx);
// Echo the results back to Ajax
echo $dataString;
exit();
}
?>
Try to comment out and execute your script I think its jQuery conflicting with it.
Related
I have two parameters ('filter', 'filter2') that I want to filter my SQLITE3 DB ('tutorial.db'); the values are then shown in DataTable. However, the table is blank every time, and although it worked with one parameter before some edits, it doesn't work for two parameters. I don't know why.
I have two files: 'index.php' and 'fetch.php'.
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Filter table</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script>
//making DataTable when HTML loads
$(document).ready(function(){
function create_list(data){
$('#tablexample').DataTable( {
destroy: true,
searching: false,
"data": data,
"columns": [
{ "data": "id" },
{ "data": "fname"},
{ "data": "lname"},
{ "data": "type"}
]
} );
}
//by default, all values are loaded to table
$.ajax({
url:'fetch.php?filter=all&filter2=all',
type:'GET',
success:function(data){
var d = JSON.parse(data);
create_list(d);
}
})
//datatable reloads when this parameter changes
$('#filter').on('change',function(){
var filter = $('#filter').val();
var filter2 = $('#filter2').val();
$.ajax({
url:'fetch.php?filter='+filter+'&filter2='+filter2,
type:'GET',
success:function(data){
var d = JSON.parse(data);
create_list(d);
}
})
}
)
//datatable reloads when this parameter changes
$('#filter2').on('change',function(){
var filter = $('#filter').val();
var filter2 = $('#filter2').val();
$.ajax({
url:'fetch.php?filter='+filter+'&filter2='+filter2,
type:'GET',
success:function(data){
var d = JSON.parse(data);
create_list(d);
}
})
}
)
})
</script>
//ignore this; some css
<style>
.checkbox {
margin-right : 5px;
font-size:16px;
}
input[type="checkbox"]{
margin-right : 5px;
}
table {
margin-top:10px;
}
table tr {
border-bottom: 1px solid #ddd;
}
table tr th {
text-transform:uppercase;
padding:5px 10px;
}
table tr td {
padding:5px 10px;
}
table tr:nth-child(odd){
background:#eee;
}
</style>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1> Jquery Ajax Filter</h1>
</div>
</div>
<p id="print"></p>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<select id="filter">
<option value="all" name="">All</option>
<option value="intern">Intern</option>
<option value="employee">employee</option>
<option value="temp">temp</option>
</select>
<select id="filter2">
<option value="all" name="">All</option>
<option value="Doe">Doe</option>
<option value="Williams">William</option>
</select>
</div>
<div class="col-md-8 col-md-offset-2" >
<table class="table table-striped" id="table">
</table>
</div>
<table id="tablexample" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Type</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
fetch.php:
<?php
if(isset($_GET['filter'],$_GET['filter2'])){
$filter = trim($_GET['filter']);
$filter2 = trim($_GET['filter2']);
if(!empty($_GET['filter'] and !empty($_GET['filter2']))){
$db = new SQLite3('tutorial.db');
if($filter == 'all' and $filter2 == 'all'){
$stmnt = $db->prepare('select * from staff');
}else{
if($filter == 'all'){
$param = '';
}else{
$param = 'type = ' + $filter + " AND ";
}
if($filter2 == 'all'){
$param2 = '';
}else{
$param2 = 'last_name = ' + $filter2;
}
// $stmnt = $db->prepare('select * from staff where type IN :type AND last_name IN :last_name');
$stmnt = $db->prepare('select * from staff where '+$param+$param2);
// $stmnt->bindParam(':type', $filter);
// $stmnt->bindParam(':last_name', $filter2);
}
$result = $stmnt->execute();
$final = array();
while ($row = $result->fetchArray()) {
$each = array(
'id'=>$row['id'],
'fname'=>$row['first_name'],
'lname'=>$row['last_name'],
'type'=>$row['type']
);
array_push($final,$each);
}
echo json_encode($final);
}
}
?>
The pasted codes are the most recent versions I have. I have tried breaking down each WHERE clause to make the passing $stmnt easier to control. Regardless, the code doesn't work for an unknown reason unfortunately.
UPDATE:
I've changed fetch.php slightly, but still nothing shows up.
if(isset($_GET['filter'],$_GET['filter2'])){
$filter = trim($_GET['filter']);
$filter2 = trim($_GET['filter2']);
if((!empty($_GET['filter']) and !empty($_GET['filter2']))){
$db = new SQLite3('tutorial.db');
if($filter == 'all' and $filter2 == 'all'){
$stmnt = $db->prepare('select * from staff');
}else{
$param = 'type = ' . $filter;
$param2 = 'last_name = ' . $filter2;
if($filter == 'all'){
if($filter2 == 'all'){
// skipped
}else{
$stmnt = $db->prepare('select * from staff where ' . $param2);
}
}else{
if($filter2 == 'all'){
$stmnt = $db->prepare('select * from staff where ' . $param);
}else{
$stmnt = $db->prepare('select * from staff where ' . $param . ' AND ' . $param2);
}
}
}
$result = $stmnt->execute();
$final = array();
while ($row = $result->fetchArray()) {
$each = array(
'id'=>$row['id'],
'fname'=>$row['first_name'],
'lname'=>$row['last_name'],
'type'=>$row['type']
);
array_push($final,$each);
}
echo json_encode($final);
}
}
?>```
Should be
$param = 'type = ' + $filter;
and
$param2 = 'last_name = ' + $filter2;
you will need another If to check if $filter1 and $filter2 are both !="all" - to insert the AND
I'm trying to implement server side pagination like datetable and I found backbone.paginator library, I don't know if there is something else.
Through their examples they used another library to help accomplishing this which is backgrid.js and its paginator plugin
Is it possible to do this pagination without Backgrid? Could you please add any example on this?
I developed the following code to share with you A JS/php code that do server site pagination and you could change it according to your need and later i may summarize it better.
First make connection to DB and create pagination table:
CREATE TABLE `pagination` (
`id` INT( 16 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 50 ) NOT NULL ,
`age` INT( 3 ) NOT NULL ,
`company` VARCHAR( 50 ) NOT NULL
)
Second insert 400 same records :
$i=0;
while ($i< 400){
$pag="insert into pagination (id,name,age,company) VALUES
('NULL','john','40','google')";
$excu=$mysqli->query($pag);
$i++;
}
Then make test.php
<!DOCTYPE html>
<html><head>
<style>
#container{overflow-x: hidden;max-width:90%;min-width:90% ;margin: 0 auto;}
td{max-width:10%;min-width:10%}
tr,td{border:1px solid black }
#page{display:inline;border:1px solid black}
#numb,#numbs{display:none}
.button{background:white}
</style>
</head>
<body >
<?php $defaultoption ="10";?>
<div id=container></div><span id=numb></span><span id=numbs><?php echo
$defaultoption;?></span>
<script type=text/javascript src=js.js></script>
</body>
</html>
Then make js.js :
onload = function (){
var container=document.getElementById("container");
var table =document.getElementById("numbs").innerHTML;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
container.innerHTML=xhttp.responseText;
var button=document.getElementById("button");
button.children[0].disabled="true";
button.children[0].style.background="yellow";
}}
xhttp.open("POST", "testa.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("table="+table);
}
function select(){
var sel =document.getElementById("select");
var table=sel.options[sel.selectedIndex].value;
var b2 =document.getElementById("numbs");
b2.innerHTML=table;
var se = new XMLHttpRequest();
se.onreadystatechange = function() {
if (se.readyState == 4 && se.status == 200) {
document.getElementById("container").innerHTML=se.responseText;
var button=document.getElementById("button");
button.children[0].disabled="true";
button.children[0].style.background="yellow";
}}
se.open("POST", "testa.php", true);
se.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
se.send("table="+table);
}
function button(button){
var b2 =document.getElementById("numbs");
var b1 =button.innerHTML;
var numb = document.getElementById("numb");
numb.innerHTML=b1;
var b= b2.innerHTML;
var butt = new XMLHttpRequest();
butt.onreadystatechange = function() {
if (butt.readyState == 4 && butt.status == 200) {
document.getElementById("container").innerHTML=butt.responseText;
var d = document.getElementsByClassName("button");
for(i=0;i<d.length;i++){
if(d[i].innerHTML == numb.innerHTML){d[i].disabled="true";
d[i].style.background="yellow";
}}}}
butt.open("POST", "testa.php", true);
butt.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
butt.send("b="+b+"&b1="+b1);
}
Make testa.php :
<?php
$pag="SELECT * FROM pagination ORDER BY id ASC ";
$exc=$mysqli->query($pag);
$numrwos =mysqli_num_rows($exc);
if($_POST['b']){
$b =$_POST['b'];
$b1 =$_POST['b1'];
$max=($b*$b1);
$m =($b1-1);
$n =($m*$b);
$min =($n-1);
if($numrwos){
echo "<select id=select onchange=select()><option selected=selected>Show Entries</option>";
if($numrwos < 11){
echo "<option>10</option>";
}elseif($numrwos > 10 && $numrwos < 26){
echo "<option>10</option><option>25</option>"; }elseif($numrwos > 25 &&
$numrwos < 51){
echo "<option>10</option><option>25</option><option>50</option>";}else{
echo "<option>10</option><option>25</option><option>50</option>
<option>100</option>";}
echo "</select><br />";
echo "<table width=80% id=table>";
echo "<tr><td width=10%>id</td><td>name</td><td>age</td><td>company</td></tr>";
$stop="0";
while ($result=mysqli_fetch_array($exc)){
if($stop > $min && $stop < $max){
echo "<tr><td>".$result['id']."</td><td>".$result['name']."</td>
<td>".$result['age']."</td><td>".$result['company']."</td></tr>";
}else{}
$stop++;
}echo "</table><br />";
echo "<div id=button>";
$i=0;
while($i < $numrwos){
$page+=$i % $b == $b-1;
$i++;
if($i%$b == 1){
$pagenum=$page+1;
echo "<button class=button onmouseover='button(this)'>".$pagenum."</button>";}}
echo "</div>";
}else{echo "no records";}
}else{
$t =$_POST["table"];
if($numrwos){
echo "<select id=select onchange=select()><option selected=selected>Show Entries</option>";
if($numrwos < 11){
echo "<option>10</option>";
}elseif($numrwos > 10 && $numrwos < 26){
echo "<option>10</option><option>25</option>"; }elseif($numrwos > 25 && $numrwos < 51){
echo "<option>10</option><option>25</option><option>50</option>";}else{
echo "<option>10</option><option>25</option><option>50</option>
<option>100</option>";}
echo "</select><br />";
echo"<table width=80% id=table>";
echo "<tr><td width=10%>id</td><td>name</td><td>age</td><td>company</td></tr>";
$stop="0";
while ($result=mysqli_fetch_array($exc)){
echo "<tr><td>".$result['id']."</td><td>".$result['name']."</td>
<td>".$result['age']."</td><td>".$result['company']."</td></tr>";
if($stop ==$t-1){break;}
$stop++;
}echo "</table><br />";
echo "<div id=button>";
$i=0;
while($i < $numrwos){
$page+=$i % $t == $t-1;
$i++;
if($i%$t == 1){
$pagenum=$page+1;
echo "<button class=button onmouseover='button(this)'>".$pagenum."</button>";}}
echo "</div>";
}else{echo "no records";}
}
?>
I wish that help you .
I did it
in the View initialize function
I call
this.reloadCustomPages();
here its implementation
reloadCustomPages: function(options) {
var self = this;
self.block();
self.customPages.fetch({data: $.param(options)}).always(function () {
self.unblock();
});
}
in the server side (java spring) I modified the api to accept new query strings
#RequestParam(value = "pageNumber", defaultValue = "1"),
#RequestParam(value = "perPage", defaultValue = "10")
and instead of returning the list directly it returns useful pagination info like
total number of items in database
current page nuber
page size
and the items itself
check this server-side snippet (I know it's not related but worthy to look at)
#RequestMapping(value = "/editor/pages", method = RequestMethod.GET)
public void listPages(#RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
#RequestParam(value = "perPage", defaultValue = "10") Integer perPage,
HttpServletResponse httpResp) throws IOException {
Long recordsTotal = pageSvc.findTotalNumberOfPages();// select count(*) from table_name
List<PbCustomPage> pages = pageSvc.findPages(pageNumber, perPage);// server side query that gets a pagenated data
BackbonePaginatorResponse response = new BackbonePaginatorResponse();// I created this simple class
response.setTotalCount(recordsTotal);
response.setPageNumber(pageNumber);
response.setPerPage(perPage);
response.setItems(pages);
httpResp.setContentType("application/json");
json.createCustomPageSerializer().addProperties().serialize(response, httpResp.getWriter());// just make your server send that obkect
}
now back the function call it will till the server to get page 1 with a page size of 10
in my template, I have this
<div class="pagination clear" style="text-align: center;">
<%= customPages.paginationHtml %>
</div>
let me tell you how I populate it
customPages.paginationHtml = this.generatePagination(customPages);
and here is the most important part
generatePagination: function (paginationResponse) {
var currentPage = paginationResponse.pageNumber,
lastPage = paginationResponse.totalCount==0?1:Math.ceil(paginationResponse.totalCount/paginationResponse.perPage);
var html = '<ul class="pagination">';
html += '<li class="'+(currentPage == 1?"disabled":"")+'" data-pb-page-number="1">««</li>';
html += '<li class="'+(currentPage == 1?"disabled":"")+'" data-pb-page-number="'+(currentPage==1?1:currentPage-1)+'">«</li>';
for (var i = 1; i <= lastPage; i++) {
html += '<li class="'+(currentPage == i?"active":"")+'" data-pb-page-number="'+i+'">'+ i +'</li>';
}
html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(currentPage==lastPage?lastPage:currentPage+1)+'">»</li>';
html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(lastPage)+'">»»</li>';
html += '</ul>';
return html;
},
each li I create it has data-pb-page-number to be used later
one more thing, how to make new requests to other pages
in the View initialize function
this.el.on('click', 'ul.pagination li:not(.disabled,.active)', this.getCustomPagesPagination);
here its implementation
getCustomPagesPagination: function (e) {
e.preventDefault();
var $el = $(e.target).closest("li");
this.reloadCustomPages({pageNumber:$el.data("pb-page-number")})
},
the the result is like this
this how I solved my problem but the question still not answered
I have some problems to Code an simple PHP ordered list that print out a random number list between 1 and 49.
The Main Code
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>AJAX</title>
<meta name="viewport" content=
"width=device-width; initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="lib/css/stil.css" />
<script type="text/javascript"
src="lib/js/script.js"></script>
</head>
<body>
<h1>Ziehung der Lottozahlen</h1>
<button id="frage">Starte die Ziehung</button>
<div id="antwort">
</div>
</body>
</html>
Here the external PHP Code to randomize the numbers
<?php
$zahlen = range (1, 49);
shuffle($zahlen);
for ($i = 0; $i < 6; $i++) {
echo $zahlen[$i] . " ";
}
?>
And here the Java script
var resOb = new XMLHttpRequest();
window.onload = function() {
document.getElementById("frage").onclick =
function () {
resOb.open('get', 'lottozahlen1.php', true);
resOb.onreadystatechange = function () {
if (resOb.readyState == 4) {
document.getElementById("antwort").innerHTML =
resOb.responseText;
}
};
resOb.send(null);
};
};
T
Now my question...how i can let Show the numbers in a ordered list?
use PHP code below way
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
You could split the string, map the values as number and sort the array. Then generate the wanted list items and put it to the wanted unordered list.
var lotto = '22 34 14 10 99',
list = lotto
.split(' ')
// .map(Number)
// .sort(function (a, b) {
// return a - b;
// })
.reduce(function (list, a) {
var li = document.createElement('li');
li.innerHTML = a;
list.appendChild(li);
return list;
}, document.createElement('ol'));
document.body.appendChild(list);
Extending Kool-Mind's answer:
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
Try adding the code below(to generate the list):
<script>
$('#button').click(function(){
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
})
</script>
Hope it helps =)
EDIT
This should be working fine now, hope it helps =)
<button id="button">Button</button>
<div id="newDiv"></div>
<script>
var clicked = false;
$('#button').click(function(){
if (!clicked){
<?php
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] = rand(1,49);
}
sort($arr,1);
?>
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
clicked = true;
}
})
</script>
This is the code i'm using:
<?php
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($"http://newsxpressmedia.com/files/radar-simulation-files")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
$files[] = $file;
$curimage++;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
#Timer_Countdown{
background:black;
color:yellow;
font-weight:bold;
text-align:center;
}
</style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
var images = <?=json_encode($files)?>;
//var images = [];
var x = -1;
var swap_hours = 0;
var swap_minutes = 0;
var swap_seconds = 5;
var down_counter_hours;
var down_counter_minutes;
var down_counter_seconds;
function initTimer() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
counter = setInterval(switcher, 1000);
}
function restartCounter() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
}
function switcher() {
down_counter_seconds--;
if (down_counter_hours <= 0 && down_counter_minutes <= 0 && down_counter_seconds <= 0) {
swapColor();
restartCounter();
}
if (down_counter_seconds <= 0 && down_counter_minutes > 0) {
down_counter_seconds = 60;
down_counter_minutes--;
}
if (down_counter_minutes <= 0 && down_counter_hours > 0) {
down_counter_minutes = 60;
down_counter_hours--;
}
document.getElementById("Timer_Countdown").innerText = down_counter_hours+":"+down_counter_minutes+":"+down_counter_seconds;
}
function swapColor() {
displayNextImage();
}
</script>
<div id="div_hours" class="div_box"></div>
<div id="div_minutes" class="div_box"></div>
<div id="div_seconds" class="div_box"></div>
<div id="div_switcher" class="div_box"></div>
</head>
<body onload = "initTimer()">
<div id="Timer_Countdown"> </div>
<img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
<button onclick="displayPreviousImage(); restartCounter()">Previous</button>
<button onclick="displayNextImage(); restartCounter()">Next</button>
</body>
</html>
The error is on the line:
var images = <?=json_encode($files)?>;
If i change this line to this line:
var images = [];
Then the code is working fine but without using the php files variable.
Something is wrong with the line: var images = <?=json_encode($files)?>;
I tried to change this line to: echo json_encode($images); or to var images = echo json_encode($files); but same error.
I'm using weebly to build my site and my site server is on ipage.com
How can i fix the error ?
It looks like you don't have short tags enabled(and are using a pre 5.4 php version), thus the line <?=json_encode($files)?> is not parsed by php and is just send straight through. var images = <... is not a valid javascript expression. Here's some information about php's short_open_tag parameter: http://php.net/manual/en/ini.core.php#ini.short-open-tag
A couple of changes. Change
$pattern ="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)";
to
$pattern = '/\.(png|jpg|jpeg|gif)$/i';
and
eregi($pattern, $file)
to
preg_match($pattern, $file)
and see what happens. eregi deprecated as PHP 5.3.0.
You are using '=' inside the PHP tags. Try this:
var images = <?json_encode($files)?>;
I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>