DataTable values not showing for multiple dropdown options (AJAX, JQuery) - javascript

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

Related

why ajax duplicate content

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()

ERROR Synchronous XMLHttpRequest on the main thread is deprecated

I am attempting to load a graph with options to show data between select dates. When I run it on my webpage, I get an error "Table has no columns." 1, but when i set the IF statement (buildchris) to NOT EQUAL to maincampus, the chart will load. I believe it has something to do with the xmlhttp .send, the variables seem to not be sending over POST (buildingchartchris). Does anyone have a solution to this problem?
buildchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$p = $_POST['purpose'];
if($p == "maincampus")
{
$sm = $_POST['sm'];
$sd = $_POST['sd'];
$sy = $_POST['sy'];
$em = $_POST['em'];
$ed = $_POST['ed'];
$ey = $_POST['ey'];
//$start_date = Date("Y-m-d", mktime(0, 0, 0, $sm, $sd, $sy));
//$end_date = Date("Y-m-d", mktime(0, 0, 0, $em, $ed, $ey));
$start_date= "2014-01-01";
$end_date= "2016-01-01";
$result = $dbc->query('SELECT SUM(actual_hours) as act_hours, Buildings.bld_name, Buildings.bld_location FROM work_orders INNER JOIN Buildings ON work_orders.building = Buildings.bld_no WHERE work_orders.actual_completion_date > "'.$start_date.'" AND work_orders.actual_completion_date < "'.$end_date.'" AND Buildings.bld_location ="0" AND Buildings.bld_name <> "N/A" AND work_orders.actual_completion_date IS NOT NULL GROUP BY Buildings.bld_name');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Building', 'type' => 'string'),
array('label' => 'Hours', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['bld_name']);
// Values of the each slice
$temp[] = array('v' => (int) $r['act_hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
}
?>
buildingchartchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$page_title = 'Dashboard';
include ('includes/header.html');
?>
<html>
<head>
<title>Dashboard</title>
<link rel="icon" href="images/NKU.png" type="image/png" sizes="16x16">
<link rel="stylesheet" href="includes/as.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js?libraries=geometry"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script>
<!--
//hides or shows the table given by nm
function hide_table(nm)
{
// alert(is_fullscreen);
var table_selector = "#table_" + nm;
$(table_selector).toggle();
//table_width = (table_width == 24)? 35:24;
//$("#iframeholder").animate({width: table_width + "%"});
}
// -->
</script> </head>
<div id="content">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Set a callback to run when the Google Visualization API is loaded.
// google.setOnLoadCallback(drawChart);
function drawChart() {
var maincamp_sm, maincamp_sd, maincamp_sy, maincamp_em, maincamp_ed, maincamp_ey;
if( document.getElementById("maincamp_dates_quarter").checked )
{
var maincamp_q = document.getElementById("maincamp_quarter").value;
maincamp_ey = Number(document.getElementById("maincamp_quarter_year").value);
maincamp_sy = maincamp_ey;
if( maincamp_q == 0 )
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
}
else if( maincamp_q == 1)
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 9;
maincamp_ed = 30;
}
else if( maincamp_q == 2 )
{
maincamp_sm = 10;
maincamp_sd = 1;
maincamp_em = 12;
maincamp_ed = 31;
}
else if( maincamp_q == 3 )
{
maincamp_sm = 1;
maincamp_sd = 1;
maincamp_em = 3;
maincamp_ed = 31;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
else if( maincamp_q == 4 )
{
maincamp_sm = 4;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
}
else
{
maincamp_sm = document.getElementById("maincamp_start_month").value;
maincamp_sd = document.getElementById("maincamp_start_day").value;
maincamp_sy = document.getElementById("maincamp_start_year").value;
maincamp_em = document.getElementById("maincamp_end_month").value;
maincamp_ed = document.getElementById("maincamp_end_day").value;
maincamp_ey = document.getElementById("maincamp_end_year").value;
}
if(!( (maincamp_ey < maincamp_sy) || ( (maincamp_em < maincamp_sm) && (maincamp_ey == maincamp_sy) ) || ( (maincamp_ed < maincamp_sd) && (maincamp_em == maincamp_sm) && (maincamp_ey == maincamp_sy) ) ))
{
var xmlhttp;
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()//Function called when there is a change of state for the server
{ //request
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)//when request is complete and no issues
{
//var str = xmlhttp.responseText;
var jsonData = $.ajax({
url: "buildchris.php",
type: "POST",
dataType: "json", // type of data we're expecting from server
async: false // make true to avoid waiting for the request to be complete
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData.responseText);
var options = {
title: 'Labor Hours for Main Campus',
is3D: 'true',
width: 1200,
height: 2000,
chartArea:{width:"40%"},
bar: {groupWidth: "50%"}
};
var maincamp_view = new google.visualization.DataView(data);
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(maincamp_view, options);
}
};
xmlhttp.open("POST","buildchris.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("purpose=maincampus&sm=" + maincamp_sm + "&sd=" + maincamp_sd + "&sy=" + maincamp_sy + "&em=" + maincamp_em + "&ed=" + maincamp_ed + "&ey=" + maincamp_ey);
}
else
{
alert("Your end date cannot be before the start date.");
}
}
google.load('visualization', '1', {'packages':['corechart']});
function cursor_hand(x)
{
x.style.cursor = "pointer";
}
function cursor_default(x)
{
x.style.cursor = "default";
}
function hide_element(nm)
{
var table_selector = "#" + nm;
$(nm).toggle();
}
</script>
<body>
<p onclick = "hide_element(operational_effectiveness_div);" style = "text-decoration: underline; font-size:x-large; font-weight:bold;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Operational Effectiveness Reports</p><br>
<div id = "operational_effectiveness_div" >
<p onclick = "hide_element(maincamp_div);" style = "text-indent: 15px; text-decoration: underline;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Show Total Labor Hours for Main Campus 2015-16</p><br>
<div id = "maincamp_div" style = "display:table;">
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_quarter" name = "maincamp_dates" value = "1" checked> Report by quarter </legend>
<p><select id = "maincamp_quarter">
<option value = 0 selected>All Quarters</option>
<option value = 1>Q1</option>
<option value = 2>Q2</option>
<option value = 3>Q3</option>
<option value = 4>Q4</option>
</select>
<input type = "number" id = "maincamp_quarter_year" min = "2015" value = "2015"></p>
</fieldset><br>
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_range" name = "maincamp_dates" value = "2"> Custom date range </legend>
<p>Start date (mm-dd-yyyy): <input type = "number" id = "maincamp_start_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_start_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_start_year" min = "2015" value = "2015"></p>
<p>End date (mm-dd-yyyy): <input type = "number" id = "maincamp_end_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_end_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_end_year" min = "2015" value = "2016"></p>
</fieldset>
<br>
<p onclick = "drawChart()" style = "border: thin solid black; padding: 2px; width: 95px; margin-left: 550px;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Generate report</p>
<div id="chart_div" style="width: 1000px; text-indent: 50px;"></div>
</div>
</div>
</body>
</html>
<?php
//Release the used resources
mysqli_close($dbc);
include ('includes/footer.html');
?>

Ordered list with random numbers between 1 and 49

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>

javascript conflict between ajax pagination and flowplayer plug-in

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.

PHP post variable is not being rendered

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 ?>

Categories

Resources