how to get values from db and insert them to events array - javascript

My code is as below.
<script>
var t=<?php echo json_encode($ta)?>;
var d=<?php echo json_encode($da)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
//$r=$ev->title;
for(var j=0;j<d.length;j++)
{
events: [{
title: t[j],
start: d[j]
}
]
}
});
});
</script>
I have used the fullcalendar 2.6.1. But nothing displayed. Please can anybody help me? I want to retrieve all the title and eventDate from the db and view in the calendar. The var t and d contains the all the data of $ta and $da arrays. I just wanted to assign them to events array title and start keywords.There are some red marks indicate that for loop is going to be wrong.

Try this one
<?php
$ta=array();
$i=0;
?>
#foreach($events as $ev)
<?php
$ta[$i]['title'] = $ev->title;
$ta[$i]['start'] = date('Y-m-d H:i:s', strtotime($ev->eventDate));
$i++;
?>
#endforeach
<script>
var t=<?php echo json_encode($ta)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: t,
eventRender: function(event, element) {
$('.fc-time', element).hide();
}
});
});
</script>

$.ajax({
url:'',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(key, value){
events.push({
title : value['title name'],
start : value['hours'],
backgroundColor: Metronic.getBrandColor('yellow'),
id : value['id']
});
});
AddFullCalenderEvent(events);
}
});
function AddFullCalenderEvent(eventList){
$('#calendar').fullCalendar({
events: eventList,
eventClick: function(event) {
// opens events in a popup window
window.location.href = "pagename?id=" + event.id;
return false;
}
Try this

Related

Show time on event mouse hover using Full calendar

I am using Fullcalendar, get call event id on event mouse hover, this event id passes in ajax call for getting the record from the database based on event id. Issue is that how to pass variable out of ajax success function. I am doing like this way
eventMouseover: function(calEvent) {
var start;
var end;
$.ajax({
url: js_base_path+ 'calendar/get_date_time/'+calEvent.id,
type:"GET",
dataType:"json",
success:function(data){
start = data.start_datetime;
end = data.end_datetime;
},
});
var realstart;
if(start == '00.00')
{
realstart = calEvent.title;
}
else
{
realstart = start+ ' - ' + end + ': ' +calEvent.title;
}
$(this).popover({
title: realstart,
content: calEvent.description,
trigger: 'hover',
template: popfunction(calEvent.borderColor),
placement: "top",
atMouse: true,
container: 'body'
}).popover('show');
},
I am facing this error when event mouse hover
Uncaught ReferenceError: start is not defined
This is my controller function
public function get_date_time($id)
{
$results = $this->calendar->get_calendar_row($id);
$data['start_datetime'] = date("H:i", strtotime($results->from_date_time));
$data['end_datetime'] = date("H:i", strtotime($results->to_date_time));
echo json_encode($data);
}

How can I send data to controller by dialog?

EDIT2: I'm trying to update my code with java, but it's not working (I suppose I miss something in controller):
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: {"graphicUrl": u, "graphicDesc": d},
success: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
$(this).dialog("close");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$("#graphicUrl").val("");
$("#graphicDesc").val("");
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
EDIT1:
Following Twisty suggestion I uptaded the dialog in order to not have any form inside (since this dialog is already in a form): https://jsfiddle.net/e57sj6hp/18/
As Twisty was also commenting, I probably need ajax, but I have to understand how use it; I think I need to use serialize() or seralizeArray(), but I don't understand well how should the controller receive the json and use it.
I have a controller like this:
public String myMethod(#ModelAttribute MyObject object, ModelMap model){...}
The object include a List of photos, and two variables url and description:
List<Photo> photos;
String url;
String description;
each photo in the list is formed by an url and a description.
In my jsp I created a dialog with jquery where a user can put an url and a description, what I want to do is to add each value into a list and send it to the controller, then clean the dialog in order to allow another submission.
I have tried a lot of but can't understand how I should do it. I'm using the spring's form and I have tried many different ways, but I think that the problem is in my javascript code. Here's one example: https://jsfiddle.net/e57sj6hp/12/
In this example the input fields and the textarea inside the dialog aren't surrounded with spring's form tags, since I've append the result inside the div and I supposed that, at the moment of the submitting, the controller should receive the data inside the form:input just created.
Not familiar with Spring, so I may miss an element, but matching what you put in your example, I can offer some potential updates.
Working Example: https://jsfiddle.net/Twisty/e57sj6hp/16/
HTML Updated
<div id="insertPhoto" style="display:none" title="Insert a Photo">
<form id="newPhoto">
<label>Url:</label>
<br/>
<input id="graphicUrl" />
<br/> Description:
<br/>
<textarea rows="4" cols="20" id="graphicDesc"></textarea>
</form>
</div>
You cannot call form.reset() without a form element. I wrapped the the form elements in a form. This has the added benefit of now responding to the form being submitted, for example if the user enters a url and hits enter.
jQuery
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc);
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$(this)[0].reset();
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
Lots of little fixes and improvements here. I moved listGraphic out of the functions, so it can be updated more globally. This allows it to be updated and read from other callbacks.
I created the function to make it a little easier to repeat.
Now regardless of how the form is submitted, the array is updated and so is the page. The dialog is closed and it's form is reset.
UPDATE 1
See new jQuery: https://jsfiddle.net/Twisty/e57sj6hp/21/
jQuery
$(document).ready(function() {
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: JSON.stringify({
"graphicUrl": u,
"graphicDesc": d
}),
complete: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
addPhoto($("#graphicUrl").val(), $("#graphicDesc").val());
// Reset values
$("#graphicUrl").val("");
$("#graphicDesc").val("");
// Close Dialog
$(this).dialog("close");
}
}
});
});

jQuery post to PHP not working without any errors

I have a jQuery dialog button, and inside it I parse all the inputs.
I want to send these parsed values to a php file, but when I click "OK" nothing happens -at all-, without any errors.
Here's my code:
$("#dialog").dialog({
autoOpen: false,
width: 'auto',
buttons: [ {
text: "Ok",
click: function() {
var functionName = $("#txtFunctionName").val();
var cassName = $("#txtClassName").val();
var classDesc = $("#txtClassDesc").val();
var input = $("#txtInput").val();
var output = $("#txtOutput").val();
/* SEND THE DATA TO addFunc.php */
var $dataStr = {'name': functionName,
'input': input,
'output': output,
'class': cassName,
'desc': classDesc};
$.post('../php/addFunc.php',
$data,
function(response){
alert("test");
}
);
$( this ).dialog( "close" );
}
}]
});
And the addFunc.php contains just a sample echo to verify correctness, but it doesn't alert anything, meaning it didn't work:
<?php
echo "Welcome";
?>
Change $dataStr to dataStr and add the correct var (dataStr no $data) in the post function.
Try this:
$("#dialog").dialog({
autoOpen: false,
width: 'auto',
buttons: [ {
text: "Ok",
click: function() {
var functionName = $("#txtFunctionName").val();
var cassName = $("#txtClassName").val();
var classDesc = $("#txtClassDesc").val();
var input = $("#txtInput").val();
var output = $("#txtOutput").val();
/* SEND THE DATA TO addFunc.php */
var dataStr = {'name': functionName,
'input': input,
'output': output,
'class': cassName,
'desc': classDesc};
$.post('../php/addFunc.php',
dataStr,
function(response){
alert("test");
}
);
$( this ).dialog( "close" );
}
}]
});

Multiple POSTs with jQuery and AJAX

I'm having an issue with posting data via AJAX through a drag and drop interface. The data indeed is hitting my POST URL as defined, however, each and every time, the POST hits twice thereby causing the processing URL to handle the data again.
The premise of my application (at least this piece of it) was starting by basically using the code found at http://jsfiddle.net/UjQVw/2/ and to modify it for my needs.
I needed to have a container of items (in this case names) that were draggable to a user-defined number of divs on the opposite side of the screen -- whereby making 'room assignments' with a list of people.
Everything, except for the double POST is working well. If anyone can assist, I'd be most appreciative!
SAMPLE HTML CODE:
<div class="parent_list">
<h1>Registrants</h1>
<ul id="unplaced" class="group">
<?
foreach ($obj->function as $key => $value)
{
?>
<li data-group-id="0" data-post-id="<?=$value["rmid"]?>">
<?=$value["lname"]?>, <?=$value["fname"]?>
</li>
<?
}
?>
</ul>
</div>
<div class="lists">
<h1>Rooms</h1>
<ul style="display:none" id="new_list" class="group"></ul>
</div>
<input type="button" id='add' value="+ Add Room"/>
SAMPLE JS
<script>
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
console.log(event);
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
});
}
});
});
</script>
You could always buffer it with a boolean.
<script>
var sending = false; //Buffering variable
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
console.log(event);
if(!sending) { //Make sure we are not already sending a request
sending = true;
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
success: {
sending = false; //Upon finishing, allow another ajax command of this type
},
error: {
sending = false;
}
});
}
}
});
});
</script>
See if that works.
After the response by #John, I did some more testing and looking around and found this gem that's apparently stumped several others by me. As stated in the original question, the POST was indeed working...it was simply posting TWICE after each event. The reason for this is that there were changes in BOTH lists, thereby initiating the callback for EACH list that's affected.
Adding this simple if check as outlined here: https://forum.jquery.com/topic/sortables-update-callback-and-connectwith
update:function(e,ui) {
if (this === ui.item.parent()[0]) {
//your code here
}
}
has done the trick for me. Hope this information helps others with multiple callbacks using jQuery sortable and connectWith functions.
So...the new JS looks like this:
<script>
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
if (this == ui.item.parent()[0]) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
});
}
}
});
});
</script>

Ajax submit of data array in CakePHP not working

I'm making making a scheduling calendar where schedulers can drag and drop members of an organization onto Fullcalendar. I have gotten as far as storing dropped events in an array Object, arrayOfEvents. I want to make an Ajax submit to a CakePHP add function to insert the data into my events database and then reload the calendar. Here's my code.
External events to drop:
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
userId: this.id
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
Fullcalendar:
/* initialize the calendar
-----------------------------------------------------------------*/
var arrayOfEvents = [];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
editable: true,
events: [
<?php foreach ($users as $user) {
foreach ($user['Event'] as $event):
?>
{
start: '<?php echo $event['start_date']; ?>',
end: '<?php echo $event['end_date']; ?>',
title: '<?php echo $event['title']; ?>',
allDay: false,
color: '#077169'
},
<?php endforeach;
}
?>
],
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.end = (date.getTime() + 3600000) / 1000; // default shift length is 1 hour
copiedEventObject.userId = originalEventObject.userId;
copiedEventObject.allDay = false;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// Push events into array
arrayOfEvents.push(copiedEventObject);
//todo: the calendar needs to insert events into the event calendar.
console.log(arrayOfEvents);
}
});
});
Update Schedule function called on a link:
function updateSchedule()
{
var arrayOfEvents = [];
//var data = "numOfEvents=" + arrayOfEvents.length; //original
var data = "numOfEvents=" + arrayOfEvents.length;
// You can get all events out of the array here
for (var i = 0; i < arrayOfEvents.length; i++) {
var event = arrayOfEvents[i];
data += "&id" + i + "=" + event.id
+ "&start" + i + "=" + event.start
+ "&end" + i + "=" + event.end;
}
// Make your ajax post here
$.ajax({
type: "POST",
url: "<?php echo $this->webroot; ?>events/add",
data: data,
success: function(response) {
alert('done!');
},
fail: function(response) {
alert("error");
}
});
Cakephp events/add function:
public function add() {
$this->autoRender = false;
if ($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
}
if (!empty($this->data)) {
if ($this->Event->save($this->data)) {
echo 'Record has been added';
} else {
echo 'Error while adding record';
}
}
}
I know this is a long one but any input would be well received.

Categories

Resources