jTable Not Displaying - javascript

I'm trying to build a website including jQuery and jTable. As such, I've been trying to use the example jTable scripts that the website provides, but I can't seem to get any input returned. The file paths all work, and I check to make sure jQuery was loaded (it was). I'm really not sure what I'm doing wrong, if anything. Thanks!
jTable file:
<html>
<head>
<link href="JQueryUI/css/smoothness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<link href="jtable/themes/standard/blue/jtable_blue.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jtable/jquery.jtable.js"></script>
</head>
<title>Under Construction</title>
Hello World
<div id="PersonTableContainer"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#PersonTableContainer').jtable({
title: 'Table of people',
actions: {
listAction: 'PersonList.php'
createAction: 'CreatePerson.php'
updateAction: 'UpdatePerson.php'
deleteAction: 'DeletePerson.php'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Author Name',
width: '40%'
},
Age: {
title: 'Age',
width: '20%'
},
RecordDate: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
$('#PersonTableContainer').jtable('load');
});
PersonList.php
<?php
$link = new mysqli("localhost", "user", "pass", "people");
$query = "SELECT * FROM people";
$results = mysqli_query($link, $query);
$rows = array();
while($row = mysqli_fetch_assoc($results))
{
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
?>
PersonList.php returns the proper output in terminal, it just doesn't seem to display anything in the website/jTable.

Try below and let me know if it works, I don't have a lot of experience with it but I even made a custom search function for it if you need it.
I use a single actions file and I use $_REQUEST for it though, not different files like you do.
//Get records from database
$result = mysql_query("SELECT * FROM people;");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);

to debug this I'd start with three angles:
1. look at the AJAX response in developer tools. In Chrome that is on the Network tab, filtering by XHR. First verify that the AJAX call is being made and look at the response.
2. verify that the AJAX response is getting into the jtable context. Just add these lines under your fields attribute:
fields: {
...
},
recordsLoaded: function(event, data) {
console.log(data);
}
3. in the browser console expand this console.log object and look at the array items. jtable is case sensitive so the resulting parameters must have the same spelling and capitalization. its usually pretty easy to just change the field names in the jtable description to match the db field names.

Related

Display get dynamic data in Chart.js with PHP and JS

I want to dynamically display statistics with Chart.js on my page from different users.
I can already display data with a clear data query from one user, but several identical bootstrap cards with different data should be displayed. How can I pass the user variables dynamicly to the mysqli_query in playerOne.php?
playerOne.php
header('Content-Type: application/json');
include "../../../includes/db.php";
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = 1";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);
stats.js
$(document).ready(function() {
showData();
});
function showData() {
{
($.post("includes/stats/playerOne.php",
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
you can send the variable on the url, here...
($.post("includes/stats/playerOne.php?user=1", // <-- add variable here -- ?user=1
then in your php, access the value of the variable using...
$_GET['user']
e.g.
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = " + $_GET['user'];

How to dispaly resources and events from database to fullcalendar?

I've been developing a full-calendar with a resource column and draggable events. I'm stuck at displaying the resources and events from the database on the calendar.
The data could be fetched successfully, as I can see it in the response tab in an array but it is not getting displayed on the calendar at all. Even the front-end doesn't seem to be working fully as while adding the resource, it is not even getting displayed temporarily. The files are getting called in the network tabs and I can see the correct results in the response tab, so I'm guessing it's the display that is not working maybe I haven't installed proper plugins or something. Can you please check what is wrong?
There were a few similar questions on this site, but everyone seemed to have different issues. I can post other related files as well, let me know if you would like to see.
Here's the code:
document.addEventListener("DOMContentLoaded", function() {
var containerEl = document.getElementById("external-events");
var checkbox = document.getElementById("drop-remove");
new FullCalendarInteraction.Draggable(containerEl, {
itemSelector: ".fc-event",
eventData: function(eventEl) {
return {
title: eventEl.innerText
};
}
});
var calendarEl = document.getElementById("calendar");
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
plugins: ["interaction", "resourceTimeline"],
header: {
left: "promptResource today prev,next",
center: "title",
right: "resourceTimelineDay,resourceTimelineWeek"
},
customButtons: {
promptResource: {
text: "+ room",
click: function() {
var title = prompt("Room name");
console.log(title);
if (title) {
fetch("add_resources.php", {
method: "POST",
headers: {
'Accept': 'text/html'
},
body: encodeFormData({"title": title}),
})
.then(response => response.text())
.then(response => {
calendar.addResource({
id: response,
title: title
});
})
.catch(error => console.log(error));
}
}
}
},
editable: true,
aspectRatio: 1.5,
defaultView: "resourceTimelineDay",
resourceLabelText: "Rooms",
resources: "all_resources.php",
droppable: true,
drop: function(info) {
if (checkbox.checked) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
},
eventLimit: true,
events: "all_events.php",
displayEventTime: false,
eventRender: function(event, element, view) {
if (event.allDay === "true") {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
eventReceive: function(info) {
console.log(calendar.getResources());
console.log(info.event);
var eventData = {
title: info.event.title,
start: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
end: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
resourceid: info.event._def.resourceIds[0]
};
console.log(eventData);
//send the data via an AJAX POST request, and log any response which comes from the server
fetch("add_event.php", {
method: "POST",
headers: {
Accept: "application/json"
},
body: encodeFormData(eventData)
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
});
calendar.render();
});
const encodeFormData = data => {
var form_data = new FormData();
for (var key in data) {
form_data.append(key, data[key]);
}
return form_data;
};
form.php
<link href='https://unpkg.com/#fullcalendar/core#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/daygrid#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/timegrid#4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/#fullcalendar/core#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/interaction#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/daygrid#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/timegrid#4.4.0/main.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<link href='https://unpkg.com/#fullcalendar/timeline#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/resource-timeline#4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/#fullcalendar/timeline#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/resource-common#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/resource-timeline#4.4.0/main.min.js'></script>
<link href="main.css" rel="stylesheet">
<script src='main.js'></script>
<div id='external-events'>
<p>
<strong>Draggable Events</strong>
</p>
<div class='fc-event'>My Event 1</div>
<div class='fc-event'>My Event 2</div>
<div class='fc-event'>My Event 3</div>
<div class='fc-event'>My Event 4</div>
<div class='fc-event'>My Event 5</div>
<p>
<input type='checkbox' id='drop-remove' />
<label for='drop-remove'>remove after drop</label>
</p>
</div>
<div id='calendar-container'>
<div id='calendar'></div>
</div>
all_resources.php
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM resources ORDER BY resourceId";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
array_push($alldata, $row);
}
echo json_encode($alldata);
?> ```
all_events.php
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM Events ORDER BY id";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
array_push($alldata, $row);
}
echo json_encode($alldata);
?>
The response from all_resources.php looks like this:
[
{"resourceId":"104","resourceTitle":"TESET"},
{"resourceId":"105","resourceTitle":"AA"},
{"resourceId":"106","resourceTitle":"HM"},
{"resourceId":"107","resourceTitle":"TEST"}
]
The response from all_events.php looks like this:
[
{"id":"65","resourceId":"104","title":"My Event 1","start":"2020-04-06","end":"2020-04-06"},
{"id":"66","resourceId":"105","title":"My Event 1","start":"2020-04-06","end":"2020-04-06"}
]
Your resource data is not in the format specified by fullCalendar. The field names you supply in the JSON must be exactly as mentioned in the resource parsing documentation - e.g. id for the resource ID, title for the title, etc. If you don't do this, fullCalendar cannot understand the data and will not display the resources.
To modify your server-side code to achieve this you have two options:
1) change your database column names in your resources table to match what fullCalendar requires. So you'd change resourceId to id and resourceTitle to title. This should be sufficient, and would not require any changes to your PHP code.
OR
2) change your all_resources.php PHP code so it generates a new array for each data row, containing the same data but with different property names, so that these names will be encoded in the JSON instead of the column names from the database:
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM resources ORDER BY resourceId";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$resource = array(
"id" => $row["resourceId"],
"title" => $row["resourceTitle"]
);
array_push($alldata, $resource);
}
echo json_encode($alldata);
?>

jQuery Full Calendar Events are not loading from Database in PHP,Codeigniter3

I implemented jQuery Full Calendar, as a separate module...That time it worked good. Now I want to show events after user logged in...User Login done... But issue with loading events only, events are added into Database.. But they won't be loaded into Calendar view
To redirect load.php, I used echo site_url('controller/method'),redirect('controller/method'). When I used redirect method it gives me 'json' data(the data which returned from load.php)
**views/calendar_view.php:**
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:'<?php echo site_url('Home/load'); ?>', /* redirect('Home/load');//<?php //$this->load->view('load')?>*/
selectable:true,
selectHelper:true,
**views/load.php:**
if($conn==false)
{
echo "Failed to connect to the Database | <br/>";
die(print_r(sqlsrv_errors(),true));
}
$timezone = new DateTimeZone("UTC");
$sql = "select * from events";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false)
{
die(print_r(sqlsrv_errors(),true));
}
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$data[] = array(
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start_event']->format("Y-m-d H:i:s"),
'end' => $row['end_event']->format("Y-m-d H:i:s")
);
}
I want to show events, after employee logged in successfully
It looks like views/load.php does not return anything, the jquery plugin expects a json object, so add the following to load.php
echo json_encode($data);
Furthermore as I remember the events in the plugin does not allow url's directly.
Therefore you will need to load the data from the url. Did not test it, but should be something like below.
$.get('<?php echo site_url('Home/load'); ?>', function(data) {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:data.parseJSON(),
selectable:true,
selectHelper:true,
});
You can check in your browser developer tools if the data was loaded correctly:
F.e. Chrome: https://developers.google.com/web/tools/chrome-devtools/network/reference

Jquery and PHP , autocomplete

So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();

Retrieve PHP Array with JSON and use the array in javascript to populate a playlist

I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);

Categories

Resources