MySQL data into FullCalendar - javascript

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

Related

php - Display Events with Form Submit (FullCalendar)

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.

AJAX pagination not loading in new posts (admin-ajax not found)

I have a custom post type built in WordPress named Knowledge.
Knowledge currently only has 4 posts in total. By default, 3 posts are shown, then on load more click, I want the last, 4th blog card to show.
However, currently, my AJAX request isn't succeeding, it gives me the /wp-admin/admin-ajax.php 403 (Forbidden) error. Similar questions stated that it might be related to security plugins. However, I have disabled any security related plugins (Jetpack) and the error still exists.
Here is my approach so far:
knowledge-listing.php
<?php
global $post;
$args = array(
'post_type' => 'knowledge',
'posts_per_page' => 3,
'post_status' => 'publish',
'orderby' => 'publish_date',
'order' => 'DESC'
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()):
$query->the_post();
get_part('templates/snippets/knowledge-card', array(
'heading' => get_the_title() ,
'subheading' => get_the_excerpt() ,
'background' => wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ,
));
endwhile;
wp_reset_postdata(); ?>
<div class="knowledgeListing__loadmore">
<a href="#" id="loadmore" class="button--loadmore" data-type="knowledge" data-max-num-pages="<?php echo $query->max_num_pages; ?>">
<?php echo _e('Load More', 'theme'); ?>
</a>
</div>
<?php
endif; ?>
loadmore.js
jQuery(function($){
$(document).ready(function(){
$("#loadmore").on('click', function (e) {
e.preventDefault();
var btn = $(this);
showNextItems(btn);
});
function showNextItems(btn) {
var max_num_pages = btn.data('max-num-pages');
var post_type = btn.data('type');
var button = btn,
data = {
'action':'loadmore',
'query': loadmore_params.posts,
'page' : loadmore_params.current_page,
// 'security' : loadmore_params.security,
// 'max_num_pages' : max_num_pages,
// 'post_type' : post_type
};
$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'Load More' ).prev().before(data);
loadmore_params.current_page++;
$('.knowledgeListing__wrapper').find('.knowledgeCard').last().after( data );
if ( loadmore_params.current_page == max_num_pages ){
button.remove();
}
console.log("success");
} else {
button.remove();
}
},
error : function(error){
button.text( 'Load More' );
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
// console.log(error);
}
});
}
});
});
The following two console.log's spit out [object Object]
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
Unsure where things are going wrong?
Edit:
console.log("Data:", data) and console.log("loadmore_params:", loadmore_params); results below:
On further inspection, when trying to access the /wp-admin/admin-ajax.php url, I see a 0. When searching for this online, it has been suggested to use die(). However, when I've added die() to the end of knowledge-listing.php, it still shows me a 0.
Here is my localized script for reference:
global $wp_query;
wp_localize_script( 'theme', 'loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("load_more")
) );
And actions:
add_action('wp_ajax_loadmore', 'pagination_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'pagination_ajax_handler'); // wp_ajax_nopriv_{action}
Just my 2 cents but "loadmore" as an action name is quite common and may be used by some other plugins/theme function. You should really consider switching to something namespaced like wp_ajax_mypluginname_loadmore.
That said, another common issue is that you perform the add_actions too late or maybe they never get hit by code before wp-admin-ajax does his thing.
Please be 100% you hit the add_actions BEFORE the code enter wp-admin-ajax.
To make a quick test you could move those line (included the function) in your child-theme functions.php file

How to add an AJAX action - Elgg

I'm trying to create an AJAX action in elgg. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:
Sorry, Ajax only!
The other error is that the page reloads, instead of persisting the data asynchronously.
What am I getting wrong? Thank you all in advance.
Below is my code:
form: views/default/forms/service_comments/add.php
<?php
$url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
$params_confirm = array(
'href' => $url_confirm,
'text' => elgg_view_icon('upload'),
'is_action' => true,
'is_trusted' => true,
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
?>
<div class="update-options">
<?= $confirm ?>
</div>
start.php
elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");
action file: actions/service_comments/add.php
<?php
elgg_ajax_gatekeeper();
$arg1 = (int)get_input('arg1');
$arg2 = (int)get_input('arg2');
// will be rendered client-side
system_message('We did it!');
echo json_encode([
'sum' => $arg1 + $arg2,
'product' => $arg1 * $arg2,
]);
Javascript : views/js/service_comments/add.js
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.
$params_confirm = array(
'href' => '#',
'text' => elgg_view_icon('upload'),
'onclick' => "myajax_function()",
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
Then move your JS code inside a function.
function myajax_function(){
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
}

Saving kartik select2 widget data with a model

Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.
I have tried this
1. the select2 widget
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
echo $form->field($model, 'unitid')->widget(Select2::classname(), [
'data' => ArrayHelper::map($model2,'unitid','unitname'),
'language' => 'de',
'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?php ActiveForm::end(); ?>
The javascript code to save data on form submit which is on the view:
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
console.log(\$form.serialize());
$.post(
\$form.attr("action"),
\$form.serialize()
)
.done(function(result) {
console.log("Succesifully saved" + result);
}).fail(function(err)
{
console.log("failed to save" + err);
});
return false;
});
JS;
$this->registerJs($script);
?>
This generates this output on the console(for the serialized form output
_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9
the output is always passed as a string that is after trying
echo json_encode($model->unitid);
On the controller it returns a string instead of an integer
that is
["5"]
How can i convert ($model->unitid) to integer for the post params
Just use
$model->unitid = (int) $model->unitid;
Thats all.

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.

Categories

Resources