FullCalendar issue while pulling data for second time on button click - ajax

I'm giving a date as an input and with the help of ajax call getting the data oriented for that particular date, while doing so I'm getting the data successfully for the first time. If i do the same the second time, I'm getting the first time data again for any date selected.
I thought the Issue to happens in this line,
$('#calendar').fullCalendar('gotoDate', NewDate);
Where i'm trying to move the calendar to the date selected, After this line im seeing the date selected getting changed to the date which is selected first time. If i refresh the page and try again it works as it believe as first request. But without this line the request for the second time is not getting completed totally.
Example: If i select the date as March-16 2015 and click on View button, I will see the list of events with start and end date in calendar for March 16, and if i try the same second time as July 13 2015, I will see the results of March 16 coming up again rather than July13.
I'm sharing my code below,
$scope.view = function(){
document.getElementById("calendar").style.display="block";
var portfolio = $scope.selectedPortfolioList.portfolio;
var period = $scope.selectedPeriod.period;
var week = $scope.selectedWeek.week;
var sDate = $("#bDate").val();
var json = { "portfolio" : portfolio, "week" : week, "period": period, "sDate":sDate};
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: false,
eventLimit: true, // allow "more" link when too many events
events: function(start, end, timezone, callback) {
$.ajax({
url: 'service/businessEvents',
dataType: 'json',
type: "POST",
data:JSON.stringify(json),
contentType: 'application/json',
mimeType: 'application/json',
success: function(response) {
var events = [];
$.each(response, function (idx,infraslist) {
var Tile=infraslist.title;
var star =infraslist.startTime;
var end = infraslist.end;
var endt = $.fullCalendar.moment(star);
endt = endt.add(end,'hours');
//Here pushing the content on calendar
events.push({
title: Tile,
start: star,
end: endt
});
});
callback(events);
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
alert('Unexpected error.'+ errorThrown);
}
}
});
},
eventClick: function(calEvent, jsEvent, view) {
if (view.name === "month") {
view.calendar.zoomTo(calEvent.start, "agendaWeek");
};
if (view.name === "agendaWeek") {
view.calendar.zoomTo(calEvent.start, "agendaDay");
};
}
});
var NewDate = moment(sDate).format('YYYY/MM/DD');
//Here the date changes after the below line. If i dont mention the below line the request stops here.
$('#calendar').fullCalendar('gotoDate', NewDate);
//
};

Related

Data missing error when using Carbon::createFromFormat in laravel [dateFormat: year-month]

I'm getting "Data Missing" error when using Carbon to pass data to pdf view in Laravel.
The query work when the data is pass back to the same page with dropdown list but getting error when pass to another page.
the error that i get
I'm using date picker as my dropdown list & the date format that I'm using is:
"2020-December"
ajax:
changeMonth:true,
changeYear:true,
showButtonPanel:true,
dateFormat: "yy-MM",
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
$('#convertBtn').click(function() {
var s = document.getElementById("sites");
var site = s.options[s.selectedIndex].text;
var startdate = $('#datepicker-8').val();
if(site != '' && startdate != '' )
{
$.ajax({
paging: false,
searching: false,
processing: true,
retrieve: true,
serverSide: true,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:"{{ route('billing.bill') }}",
type:"GET",
dataType:"json",
data:{
site:site,
startdate:startdate,
},
success:function(data){
alert(JSON.stringify(data));
},
error: function(data){
alert('Error');
}
})
}
else
{
alert("Please select 'Site' & 'Date'. ");
}
});
controller
$sites['report_date'] = Carbon::createFromFormat('Y-F', $request->startdate);
$data = DB::table('monthly_data')
->where('site', $request->site)
->whereMonth('report_date', $sites['report_date'])
->whereYear('report_date',$sites['report_date'])
->get();
$pdf = \App::make('dompdf.wrapper');
$pdf -> loadView('pdf',compact('data'));
$pdf -> setPaper('a4','landscape');
return $pdf->stream('report.pdf');
may i know how to solve this error?
solution:
do some changes in ajax
data: {
site: site,
startdate: startdate,
},
xhrFields: {
responseType: 'blob' // to avoid binary data being mangled on charset conversion
},
success: function(blob, status, xhr) {
var ieEDGE = navigator.userAgent.match('/Edge/g');
var ie = navigator.userAgent.match('/.NET/g'); // IE 11+
var oldIE = navigator.userAgent.match('/MSIE/g');
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var fileURL = URL.createObjectURL(blob);
document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
}
},
error: function(data) {
alert('Error');
}
remove dataType:"json"; and replace it with xhrFields: { responseType: 'blob'} then it works

Slick grid values not populating in the grid

I am trying to populate slick grid it is showing the values while debugging but not showing in the web page.
I have added all the required references. Here is the js function.
function LoadMonthStatus(dropdownYear, buttonId) {
try {
$(".screen").css({ opacity: 0.5 });
$(".slick-cell").css({ opacity: 0.5 });
dirtyFlag = false;
var drpYear = document.getElementById(dropdownYear);
year = drpYear.options[drpYear.selectedIndex].value;
data = [];
var dropdownoptions = ""; // "hard,soft,closed";
var columns = {};
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true,
autoHeight: true
};
columns = [
{ id: "month", name: "Month", field: "Month", width: 250 },
{ id: "status", name: "Close Status", field: "Status", options: columnOptions, editor: Slick.Editors.Select, width: 150 }
];
$.ajax({
type: "GET",
url: "http://localhost:51072/PULSE.Service/api/MonthCloseStatus/LoadMonths",
data: { year: $("#drpYear").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
data = msg;
monthStatusGrid = new Slick.Grid("#slkgrdMonths", data, columns, options);
//grid.setSelectionModel(new Slick.CellSelectionModel());
monthStatusGrid.onCellChange.subscribe(function (e, args) {
var cell = monthStatusGrid.getCellNode(args.row, args.cell);
cell.className += cell.className ? ' slick-cell-modified' : 'slick-cell-modified';
dirtyFlag = true;
});
if (msg == null || msg == "")
document.getElementById(buttonId).disabled = true;
else
document.getElementById(buttonId).disabled = false;
//Enable the button
$(".screen").css({ opacity: 1 });
$(".slick-cell").css({ opacity: 1 });
},
error: function (xhr, textStatus, errorThrown) {
try {
var err = JSON.parse(xhr.responseText);
jAlert(err.Message, 'PULSE');
}
catch (e) {
jAlert(clientErrMessage, 'PULSE');
}
$(".screen").css({ opacity: 1 });
$(".slick-cell").css({ opacity: 1 });
}
});
}
catch (e) {
jAlert(clientErrMessage, 'PULSE');
}
}
Slick grid should be populated with months like Jan, Feb, March and its status respectively in 2 columns.
There are too many variables to give an answer. However I would recommend that you create the grid on page load and just populate it with data on ajax load, rather than creating the grid possibly each time.
In my experience, data not being visible is often CSS related.
Have a look at the samples in the SlickGrid repo, they are pretty comprehensive. Make sure you are using https://github.com/6pac/SlickGrid rather than the old MLeibman repo.
If you want assistance, the best idea is to create a stand alone test page that works with local files (apart from the ajax call) in the example folder of the slickgrid repo.
If you can share that, we can easily reproduce the behaviour. As a bonus, about 90% of the time you'll work out the problem while you are creating the example page.
Check to see
-if the property of data after ajax call is matching with the property provided in columns Field and vice versa.
- if the container u are passing is correct.

Youtube search autocomplete not working with Framework 7

I am trying to use Framework 7 autocomplete feature with youtube search API v3. I had used search api for autocomplete using Jquery UI. Framework 7 has also Ajax autocomplete feature. But my code is not working with Framework 7.
Here is my youtube search autocomplete js code for jquery UI, that works 100% and shows up video search suggestion on text input
//code for auto complete using jquery UI works perfect
jQuery( "#vid-search" ).autocomplete({
source: function( request, response ) {
//console.log(request.term);
var sqValue = [];
jQuery.ajax({
type: "POST",
url: "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1",
dataType: 'jsonp',
data: jQuery.extend({
q: request.term
}, { }),
success: function(data){
console.log(data[1]);
obj = data[1];
jQuery.each( obj, function( key, value ) {
sqValue.push(value[0]);
});
response( sqValue);
}
});
},
select: function( event, ui ) {
setTimeout( function () {
youtubeApiCall();
}, 300);
}
});
And here is my youtube search autocomplete code with framework 7, Doest show up video search suggestions on text inpute..
var autocompleteDropdownAjax = myApp.autocomplete({
input: '#autocomplete-dropdown-ajax',
openIn: 'dropdown',
preloader: true, //enable preloader
valueProperty: 'id', //object's "value" property name
textProperty: 'name', //object's "text" property name
limit: 20, //limit to 20 results
dropdownPlaceholderText: 'Try "JavaScript"',
expandInput: true, // expand input
source: function (autocomplete, query, request, response, render) {
var results = [];
if (query.length === 0) {
render(sqValue);
return;
}
// Show Preloader
autocomplete.showPreloader();
// Do Ajax request to Autocomplete data
$$.ajax({
type: "POST",
url: "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1",
dataType: 'jsonp',
data: jQuery.extend({
q: request.term
}, { }),
success: function (data) {
// Find matched items
console.log(data[1]);
obj = data[1];
jQuery.each( obj, function( key, value ) {
sqValue.push(value[0]);
});
response( sqValue);
// Hide Preoloader
autocomplete.hidePreloader();
// Render items by passing array with result items
render(sqValue);
}
});
},
select: function( event, ui ) {
setTimeout( function () {
youtubeApiCall();
}, 300);
}
});
That is because the jSon result should be in a special format, the result rendered by the API looks like:
["funn",["funny vines","funny videos 2016","funny videos","funny","funnel vision","funny cat videos","funny fails","funny pranks","funny cats","funny songs"]]
First parent array has the query you typed, second child array has the result array, you must push the child array to the result.
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i])
}
And here is the result:
Full code:
var autocompleteDropdownAjax = myApp.autocomplete({
input: '#autocomplete-dropdown-ajax',
openIn: 'dropdown',
preloader: true, //enable preloader
valueProperty: 'value', //object's "value" property name
textProperty: 'text', //object's "text" property name
limit: 20, //limit to 20 results
dropdownPlaceholderText: 'Search Youtube',
expandInput: true, // expand input
source: function(autocomplete, query, render) {
var results = [];
var returned = [];
if (query.length === 0) {
render(results);
return;
}
// Show Preloader
autocomplete.showPreloader();
// Do Ajax request to Autocomplete data
$$.ajax({
url: 'http://suggestqueries.google.com/complete/search?client=firefox&ds=yt',
method: 'GET',
crossDomain: true,
dataType: 'json',
//send "query" to server. Useful in case you generate response dynamically
data: {
q: query
},
success: function(data) {
// Find matched items
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i])
}
// Hide Preoloader
autocomplete.hidePreloader();
// Render items by passing array with result items
render(results);
}
});
}
});
I hope this helps :)

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

How can I load all events on calendar using Ajax?

I want to load all events on FullCalendar using AJAX when I clicked next-previous-button in agenda-views.
I guess, when will click on next-previous-button then I'll send current date('y-m-d') to url: 'fetch-events.php' then it will return event{ id: ,title: , start: , end: , allDay: } format data for rendering on calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: false,
selectHelper: false,
editable: false,
events: // on-click next-previous button load events using Ajax
// post date using Ajax, then query to fetch all events and return data
});
JSON not working in my case
From the FullCalendar Online Documentation
FullCalendar will call this function whenever it needs new event data.
This is triggered when the user clicks prev/next or switches views.
This function will be given start and end parameters, which are
Moments denoting the range the calendar needs events for.
timezone is a string/boolean describing the calendar's current
timezone. It is the exact value of the timezone option.
It will also be given callback, a function that must be called when
the custom event function has generated its events. It is the event
function's responsibility to make sure callback is being called with
an array of Event Objects.
Here is an example showing how to use an event function to fetch
events from a hypothetical XML feed:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
Source
I made some little changes:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format()
},
success: function(doc) {
var events = [];
if(!!doc.result){
$.map( doc.result, function( r ) {
events.push({
id: r.id,
title: r.title,
start: r.date_start,
end: r.date_end
});
});
}
callback(events);
}
});
}
});
Notes: start and end MUST be ISO 8601. Another change was the use of format instead of unix (this made easier for me to deal with the code-behind)
There is a built in option avaliable
var calendar = new FullCalendar.Calendar(calendarEl, {
events: '/myfeed.php'
})
more details https://fullcalendar.io/docs/events-json-feed
This is perfect way to load data properly.
// if you want to empty events already in calendar.
$('#calendar').fullCalendar('destroy');
$.ajax({
url: 'ABC.com/Calendar/GetAllCalendar/',
type: 'POST',
async: false,
data: { Id: 1 },
success: function (data) {
obj = JSON.stringify(data);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
/* 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
};
// 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
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
//isRTL: true,
buttonHtml: {
prev: '<i class="ace-icon fa fa-chevron-left"></i>',
next: '<i class="ace-icon fa fa-chevron-right"></i>'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//obj that we get json result from ajax
events: JSON.parse(obj)
,
editable: true,
selectable: true
});
fullCalendar already uses ajax, so you don't have to type it. When I was starting to implement fullCalendar I used the solution of the most voted answer here:
https://stackoverflow.com/a/25404081/3927450
but then I could prove, that fullCalendar is in charge of making the ajax call the times the view changes without you having to do anything. I find this plugin very useful, although the documentation did not seem very clear to me.
So this code:
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
is exactly this:
events: schedule.php/load,
you only have to provide the url. Off course you have to deal with a proper JSON response from the server. Or if you need more params you can do it like this:
events: {
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
var events= '';
$.ajax({
url: '/eventoscalendar',
dataType: 'json',
type: 'GET',
success: function(data) {
events= JSON.stringify(data);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
displayEventTime: true,
selectable: true,
droppable: false,
events: JSON.parse(events)
});
}
});
y en /eventoscalendar
public function eventoscalendar()
{
$events[]= [
"title" =>'Meeting',
"start"=> date('Y-m-d'),
"allDay"=> false,
"url"=> 'http://google.com/'
];
return JsonResponse::create($events, 200, array('Content-Type'=>'application/json; charset=utf-8' ));
}

Resources