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 ?>
Related
Hello I am new here and working on a project that requires this option of "Viewing content in DIV .posts_area, from database using AJAX",
I had a problem that the content I get in .posts_area sometimes duplicate itself.
Can anyone help me with the solution and I would also be happy for more detailed explanation about the subject.
// AJAX in
<script type="text/javascript">
$(document).ready(function() {
var flag = 0;
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': 0,
'limit': 6
},
async: true,
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': flag,
'limit': 5
},
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
}
});
});
</script>
//getData.php
<?php
include ('config/config.php');
include 'includes/classes/user.php';
include 'includes/classes/post.php';
if(isset($_GET['offset']) && isset($_GET['limit'])){
$limit = $_GET['limit'];
$offset = $_GET['offset'];
$data = mysqli_query($con,"SELECT * FROM posts WHERE deleted='no' ORDER by id DESC LIMIT {$limit} OFFSET {$offset} ");
if(mysqli_num_rows($data ) > 0) {
while($row = mysqli_fetch_array($data) ){
$id = $row['id'];
$comments_check = mysqli_query($con, "SELECT * FROM comments WHERE post_id='$id'");
$comments_check_num = mysqli_num_rows($comments_check);
?>
<script>
function myFunction<?php echo $id; ?>() {
var x = document.getElementById("toggleComment<?php echo $id; ?>");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<?php
$added_by_user = $row['added_by_user'];
$post_profile_pic = $row['post_profile_pic'];
$added_by = $row['added_by'];
$body = $row['body'];
$date_time = $row['date_added'];
$user_session = $_SESSION['user'];
if($user_session == $added_by_user)
$delete_button = "<form action = 'delete_post.php?id=$id' method='POST' id = 'delete_post_id_form'>
<input type ='submit' class = 'delete_post_class_input' id = 'delete_post_id_input' value = 'Delete'></input>
</form>";
else
$delete_button = "";
// if($user_session == $added_by_user)
// $update_button = "<form action = 'update_post.php?post_id=$id' method='POST'>
// <input type ='submit' class = 'update_post_class' id = 'update_post_id' value = 'Update'></input>
// </form>";
// else
// $update_button = "";
$str .= "<div class='status_post' >
<div class='on_post_profile_pic_class' id = 'on_post_profile_pic_id'>
<a href='$added_by_user' class='posted_by_on_img'><img src='$post_profile_pic' width='50' id = 'on_post_profile_img_id'></img></a>
</div>
<div class='posted_by1' id='added_by_on_post' style='color:#ACACAC;'>
<a href='$added_by_user' class='posted_by'> $added_by </a>
</div>
<img src='assets/images/icons/more_info_button_black_down.png' onClick='show_hide()'alt='more_info_on_post_button_black_down_button_alt' class='more_info_on_post_button_black_down_btn' id ='more_info_on_post_button_black_down_btn_id' name ='more_info_name'></img>
<img src='assets/images/icons/more_info_button_black_up.png' alt='more_info_on_post_button_black_up_button_alt' class='more_info_on_post_button_black_up_btn' id ='more_info_on_post_button_black_up_btn_id'></img>
<div class = 'date_added_on_post_class' id = 'date_added_on_post_id'>$date_time</div>
<div class = 'update_post_class' id = 'update_post_id'>$update_button</div>
<div class = 'delete_post_class_div' id = 'delete_post_id'>$delete_button</div>
<div id='post_body' dir=auto>
$body
</div>
</div>
</div>
<div class='span_class' id='span_id' onclick='myFunction$id()' >Comments($comments_check_num) </div>
<hr>
<div class='post_comment' id='toggleComment$id' >
<iframe src='comment_frame.php?post_id=$id' class = 'comment_iframe_class' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr class ='hr'>";
}
echo $str;
}
}
?>
$('.posts_area').html(data);
Use this instead of append()
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>
I am creating a file upload script.
What I wanted to do is to upload the file without refreshing the page
Here's my code:
upload.php
<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>
</body>
</html>
I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible.
By the way, is it possible for this to run without using any plugins or libraries?
I managed to find a solution for this. I separated the php script from the html and add a javascript file. I used ajax to call the PHP file to upload the files.
Here's my code;
index.php
<html>
<head>
<style type="text/css">
.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px;
}
.uploads a, .uploads span{
display: block;
}
.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px;
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}
.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
for(x=0; x<data.succeeded.length; x = x+1){
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
</body>
</html>
upload.php
<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
anyways, thanks for the help guys. those were gladly appreciated.
Thanks!
I think in your case the simplest way is to put it into an iframe. I assume you have all code in one PHP file which is called upload.php. You would get something like this:
<?php
//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
echo '
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
<input type="file" name="file1[]" id="file1" multiple>
<input type="submit" value="Upload File">
</form>';
exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<!-- IFrame which loads the form !-->
<iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>
Showing uploaded image after successful upload
you just go through with this code I have already given the answer of this type of question
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 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.