How to dispaly resources and events from database to fullcalendar? - javascript

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

Related

lib fullCalendar, calendar isn't rendering in the page... i'm using contats and events in my calendar

my homepage is the callendar and look like this:
<?php
include_once("banco/conexao.php");
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='https://cdn.jsdelivr.net/npm/fullcalendar#6.1.4/index.global.min.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listYear'
},
views: {
listYear: {
type: 'listYear',
buttonText: 'Year'
}
},
initialView: 'dayGridMonth',
locale: 'pt-br',
events: [
<?php include 'eventos_json.php'; ?>
<?php include 'contatos_json.php'; ?>
]
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
I created 2 files to prepare the event and contact data
my event_json.php file:
<?php
include_once 'banco/conexao.php';
// database connection
$conn = getConexao();
// recover events from database
$queryEventos = "SELECT * FROM eventos";
$resultEventos = mysqli_query($conn, $queryEventos);
// Convert event information into a format that FullCalendar understands
$eventos = array();
while ($evento = mysqli_fetch_assoc($resultEventos)) {
$nomeEvento = $evento['nomeEvento'];
$dataEvento = $evento['dataEvento'];
$horaEvento = $evento['horaEvento'];
$tipoEvento = $evento['tipoEvento'];
$organizadorEvento = $evento['organizadorEvento'];
$telefoneEvento = $evento['telefoneEvento'];
$localEvento = $evento['localEvento'];
$eventos[] = array(
'title' => $nomeEvento,
'start' => $dataEvento . 'T' . $horaEvento,
'extendedProps' => array(
'tipoEvento' => $tipoEvento,
'organizadorEvento' => $organizadorEvento,
'telefoneEvento' => $telefoneEvento,
'localEvento' => $localEvento,
),
);
}
mysqli_close($conn);
echo json_encode($eventos);
?>
my contact_json.php file
<?php
include_once 'banco/conexao.php';
$conn = getConexao();
$queryContatos = "SELECT * FROM contatos";
$resultContatos = mysqli_query($conn, $queryContatos);
$contatos = array();
while ($contato = mysqli_fetch_assoc($resultContatos)) {
$nomeContato = $contato['nomeContato'];
$dataNascContato = $contato['dataNascContato'];
$emailContato = $contato['emailContato'];
$telefoneContato = $contato['telefoneContato'];
$sexoContato = $contato['sexoContato'];
$contatos[] = array(
'title' => $nomeContato,
'start' => $dataNascContato,
'allDay' => true,
'extendedProps' => array(
'emailContato' => $emailContato,
'telefoneContato' => $telefoneContato,
'sexoContato' => $sexoContato,
),
);
}
// Retorna os contatos no formato JSON
mysqli_close($conn);
echo json_encode($contatos);
?>
i'm not from a english country, so my code is in another language (portuguese)
my localhost is like this,
the calendar is not showing :
im here because not even chatgbt can help me anymore

How to update an event in the database by dragging/dropping an external event in JavaScript and PHP?

I'm developing a calendar by using the full-calendar JavaScript library. I've the front-end ready but I'm not sure on how to update the event data in the database, after it gets dropped on the calendar. I'm very new to JavaScript, I've referred to a few similar questions but didn't get exactly what I'm looking for.
Here's my code:
**index.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>
<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>
** main.js**
document.addEventListener('DOMContentLoaded', function() {
var Calendar = FullCalendar.Calendar;
var Draggable = FullCalendarInteraction.Draggable;
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('calendar');
var checkbox = document.getElementById('drop-remove');
new Draggable(containerEl, {
itemSelector: '.fc-event',
eventData: function(eventEl) {
return {
title: eventEl.innerText
};
}
});
var calendar = new Calendar(calendarEl, {
plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
editable: true,
droppable: true,
drop: function(info) {
if (checkbox.checked) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
},
});
calendar.render();
});
**add_event.php**
require 'database.php';
echo $_POST['title'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO Events (title, start, [end]) VALUES (:title, :start, :end)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
$conn->rollback();
return false;
}
Here's a link to the codepin which I referred to : https://fullcalendar.io/docs/external-dragging-demo
I'm just not sure on how do I get the javascript to link to the insert function. So when the event gets dropped, it should get saved in the database.
You need to handle the eventReceive callback in fullCalendar. This will give you the associated event data from the dropped item. You can then send that data to add_event.php using AJAX. See https://fullcalendar.io/docs/eventReceive for more details of the callback.
Something like this should work:
eventReceive: function( info ) {
//get the bits of data we want to send into a simple object
var eventData = {
title: info.event.title,
start: info.event.start,
end: info.event.end
};
//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));
}
Note: I've used the modern fetch() function to perform the AJAX call, rather than the older XmlHttpRequest, or anything which would rely on jQuery or another external library.
And here's the code for the encodeForm function which the above code makes use of (credit to this site for the idea):
const encodeFormData = (data) => {
var form_data = new FormData();
for ( var key in data ) {
form_data.append(key, data[key]);
}
return form_data;
}
Demo:
document.addEventListener('DOMContentLoaded', function() {
var Calendar = FullCalendar.Calendar;
var Draggable = FullCalendarInteraction.Draggable;
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('calendar');
var checkbox = document.getElementById('drop-remove');
new Draggable(containerEl, {
itemSelector: '.fc-event',
eventData: function(eventEl) {
return {
title: eventEl.innerText
};
}
});
var calendar = new Calendar(calendarEl, {
plugins: ['interaction', 'dayGrid', 'timeGrid'],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
editable: true,
droppable: true,
eventReceive: function(info) {
//get the bits of data we want to send into a simple object
var eventData = {
title: info.event.title,
start: info.event.start,
end: info.event.end
};
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;
}
<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>
<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>
P.S. You should also urgently fix the SQL injection vulnerability in your PHP code, as I mentioned in the comments above.

MySQL data into FullCalendar

EDIT 2
I have the array at the correct format but nothing added to calendar:
EDIT
I want to get data from mysql and display it on fullcalendar. I have this PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$eventss = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment INNER JOIN patient ON appointment.patient_id = patient.id WHERE appointment.id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array( 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($event);
?>
The array that should be returned to fullcalendar so it can display it should be like:
'id'=>'value', 'title'=>'my title', 'start'=>...etc
But what the array I am seeing in the XHR is like:
Here is fullcalendar script (no errors at the console):
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: 'fullcalendar/get-events.php',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
});
})(jQuery);
</script>
I think you have problem with array you are using and you dont have ID for event, it supposee patient id to b I made some changes on your code please try it .
foreach($search_date_stmt_fetch as $row)
{
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',strtotime($row['date_app'])), 'end' => date('Y-m-d',strtotime($row['date_app'])), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
You are mixing $event, $events and $eventss (unused).
It should read :
foreach($search_date_stmt_fetch as $row) {
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
it depends on version of full calendar , there are two version v2 , v1
the required properties for the event object is title,start
if you are working with version v2, u need to convert the date to Moment, the version v2 is completely working on moment objects.
after getting the data from server, we can convert it like this
in js file:
$.map(data, function (me) {
me.title = me.title, // this is required
me.start = moment(me.start).format(); // this is required
me.end = moment(me.end).format();
}
$('#calendar').fullCalendar('addEventSource', data);

Autocompleting a form in PHP/Javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

jTable Not Displaying

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.

Categories

Resources