php - Display Events with Form Submit (FullCalendar) - javascript

Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. "meeting")
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I'm missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.

Related

autocomplete data does not appear in bootstrap modal, but only the list appears

I have a problem autocomplete the bootstrap modal. when I enter the keyword search for the book, but only black dots appear. any solution to this?
things that happen as you can see in the image, I've tried adding CSS z-index but the results are still the same.
public function CheckingBook()
{
if ($this->input->is_ajax_request()) {
if ( isset($_GET['term']) ) {
$result = $this->book_model->GetBookByTitle($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row) {
$data[] = array(
'judul_buku' => $row['judul_buku'],
'isbn_buku' => $row['isbn_buku'],
'kode_buku' => $row['kode_buku']
);
}
} else {
$data = [
'msg' => 'error',
'gagal' => 'Tidak ada data yang ditemukan'
];
}
} else {
$data = [
'msg' => 'error',
'gagal' => 'Tidak ada data yang di inputkan'
];
}
echo json_encode($data);
} else {
$this->session->set_flashdata('error', 'Tidak punya akses langsung kehalaman tersebut');
redirect(base_url('adminpage/book'),'refresh');
}
}
this is jquery autocomplete
$('#bookTitleAdd').autocomplete({
source: '/perpustakaan/adminpage/book/CheckingBook',
select : function (event,ui) {
$('#bookTitleAdd').val(ui.item.judul_buku)
$('#bookISBNAdd').val(ui.item.isbn_buku)
}
});
<input type="text" name="judulBuku" class="form-control" id="bookTitleAdd" placeholder="Judul Buku" autocomplete="off">
I try to look at the xhr network and then see the data objects in the array
I had the same problem. It's because of z-index. Boostrap modal has z-index=1050. jquery-ui menu has z-index=100.
You can use this:
.ui-menu.ui-autocomplete.ui-front {
z-index: 1100;
}
$data[] = array(
'label' => $row['judul_buku'], //solved this
'judul_buku' => $row['judul_buku'],
'isbn_buku' => $row['isbn_buku'],
'kode_buku' => $row['kode_buku']
);

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

wordpress custom query - orderby title will not work

I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.

yii cgridview update depending on dropdownlist

I'm newbie with Yii.
I have a CGridview with a cutom dataprovider which takes a parameter $select:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'beneficiary-grid',
'dataProvider' => $model->searchForVoucherAssignment($select),
'filter' => $model,
'columns' => array(
'id',
'registration_code',
'ar_name',
'en_name',
'family_member',
'main_income_source',
'combine_household',
array( 'class'=>'CCheckBoxColumn', 'value'=>'$data->id', 'selectableRows'=> '2', 'header' => 'check',
),
),
));
That parameter $select takes its values from dropdownlist:
$data = CHtml::listData(Distribution::model()->findAll(array("condition"=>"status_id = 2")), 'id', 'code');
$select = key($data);
echo CHtml::dropDownList(
'distribution_id',
$select, // selected item from the $data
$data,
array(
)
);
So I defined a script to update the CGridview depending on the value of dropdownlist
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
$.fn.yiiGridView.update('beneficiary-grid', {
data: $(this).serialize()
});
return false;
});
");
My model:
public function searchForVoucherAssignment ($distribution_id = 0) {
$criteria = new CDbCriteria;
if ($distribution_id != 0) {
$criteria->condition = "Custom Query...!!";
}
$criteria->compare('id', $this->id);
//Custom Criteria
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 20,
),
));
}
The problem is that the CGridview isn't changing where a value of the dropdownlist changed...
I think you have selected the wrong Id for the change event. The Id should be
$('#distribution_id').change(function() {

how to add live updating charts in yii with highchart

Am using Yii and Activehighcharts to show charts.
http://www.yiiframework.com/extension/activehighcharts
controller is as follows
public function actionChartView(){
$dataProvider=new CActiveDataProvider('ChartData',array(
'criteria'=>array(
'condition'=>'dID=2',
'order'=>'time ASC',
),
'pagination'=>array(
'pageSize'=>50,
),
)
);
$p=$dataProvider->pagination;
$p->setItemCount($dataProvider->getTotalItemCount());
$p->currentPage=$p->pageCount-1;
if(isset($_GET['json']) && $_GET['json'] == 1){
$count = ChartData::model()->count();
for($i=1; $i<=$count; $i++){
$data = ChartData::model()->findByPk($i);
$data->data += rand(-10,10);
$data->save();
}
echo CJSON::encode($dataProvider->getData());
}
else{
$this->render('ChartView',array('dataProvider'=>$dataProvider,));
}
}
View as
$this->Widget('ext.ActiveHighcharts.HighchartsWidget', array(
'dataProvider'=>$dataProvider,
'template'=>'{items}',
'id'=>'Temperature',
'options'=> array(
'title'=>array(
'text'=>'Temperature'
),
'chart'=>array(
"zoomType"=>'x',
),
'xAxis'=>array(
'title' => array('text' => 'Time',),
'categories' => 'time',
'labels' => array(
'rotation' => -90,
'y' => 20,
),
),
'yAxis'=>array(
'title' => array('text' => 'DegC'),
),
'series'=>array(
array(
'type'=>'areaspline',
'name'=>'Temperature', //title of data
'dataResource'=>'data', //data resource according to datebase column
)
),
)
));
i need to update the chart in every 2 minutes with ajax.
also i need to get old data.
how to handle these scenarios.
in your ajax call success call back update the data in the chart using the api methods provided in highcharts documentation.
please refer this link it will help you to find a good solution.
Ok. To best answer your question i will try to clear things as much as possible.
First you need to create a view (a php file that will contain your highchart code)
Second you need to edit your Controller (let's assume siteController) and create an action to call the view you've just create. Inside that action you will need to connect and query the database.
See the below sample code:
siteController action:
public function actionAtencionesMensuales() {
$sql = Yii::app()->db->createCommand('
SELECT DISTINCT MONTH(hora) as mes, count(*) as total
FROM visitas
WHERE YEAR(hora)=YEAR(CURDATE())
GROUP BY MONTH(hora)')->queryAll();
$mes = array();
$total = array();
for ($i = 0; $i < sizeof($sql); $i++) {
$mes[] = $sql[$i]["mes"];
$total[] = (int) $sql[$i]["total"];
}
$this->render('my_view', array('mes' => $mes, 'total' => $total));
}
}
In the View:
<?php
$this->Widget('ext.highcharts.HighchartsWidget', array(
'options' => array(
'exporting' => array('enabled' => true),
'title' => array('text' => 'Mes'),
'theme' => 'grid',
'rangeSelector' => array('selected' => 1),
'xAxis' => array(
'categories' => $mes
),
'yAxis' => array(
'title' => array('text' => 'Cantidad')
),
'series' => array(
array('name' => 'Total', 'data' => $total = array_map('intVal', $total)),
)
)
));
?>
Within the series of the chart, it's better to use when calling the variable:
$total = array_map('intVal', $total)
Instead of just:
$total
Good luck :)

Categories

Resources