unable to create dynamic events in fullcalendar - javascript

i have a situation in which i m trying to create events dynamically using the plugin fullcalendar im trying to create events with the help of the ajax call and the data retrieved is in the form of json
when i m trying to create events only event at index 0 is getting created rest of events are not created
the javascript code is as follows
function showData()
{
var ids = showValidData();
if (ids.length != 0)
{
$.ajax({
url: $("#base-url").val() ,
type: 'POST',
data: {'ids': ids},
dataType: 'json',
success: function (response)
{
var data = response.data;
var myevents = [];
if (response.success)
{
$(data).each(function (index, value) {
myevents.push({
title: value.layoutName,
start: value.startDate,
end: value.endDate
});
});
console.log(myevents);
$(".fc-event-container").click();
$('#calendar-example-1').fullCalendar({
events: myevents,});
return;
}
}
});
}
}

Set events when initializing FullCalendar - define the url of the script that returns a json of events from your database (https://fullcalendar.io/docs/event_data/events_function/). If you want to dynamically refresh the calendar , you can add a setInterval ontop:
$(document).ready(function(){
setInterval(function(){$('#calendar').fullCalendar('refetchEvents')}, 30000);
$("#calendar").fullCalendar({
...
events: {
url: 'script.php',
type: 'POST',
data: {
data1: x,
data2: y
},
success : function(response){
// do something
},
}
});
});

Related

Issue in displaying events in Fullcalendar.js

Hi I am trying to implement FullCalendar.js with Asp.Net MVC. I am abl to show empty calendar but my events are not getting loaded in the Calendar.
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",
success: function (doc) {
debugger;
$('#calendar').fullCalendar();
var events = [];
$(doc).find('[object Object],[object Object]').each(function () {
debugger;
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
// });
$('#calendar').fullCalendar('refetchEvents');
// callback(events);
}
});
it comes to success method and it has two events in it . but dont know why theseevents are not loaded into FullCalendar and also after this Calendar is not comingg automatically.
I guess it is not going in events.push. When I do hover on doc it shows "[object Object],[object Object]" and in this it has two records on [0] and [1].
Please help me in this.
Try using
$('#calendar').fullCalendar( 'rerenderEvents' )
after your events have been pulled.
Also, make sure to use the code from the official documentation properly. Try the following (untested):
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",,
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);
}
});
}
});
If you now want to refetch your events, call :
$('#calendar').fullCalendar('refetchEvents');
where necessary.
EDIT:
Since your are actually pulling data from a JSON feed, the following code may even be enough:
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary'
});
Check the documentation here:
EDIT2:
To dynamically modify the request you send to the backend (depending on a dropdown or something else), may be achieved as follows:
var myValue = 10;
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary',
data: function() { // a function that returns an object
return {
dynamic_value: myValue
};
}
});

How to reset the data after init , Select2

I use Select2-4.0.0 I have been struggling with this problem for a whole day that to update the data.
I search every posts I can like Update select2 data without rebuilding the control, but none have them work.
What I need is really simple (a setter to data):
I have a diaglog, which had a select. Every time I open the diaglog, I will ajax for an data to keep it in a local array like:
when dialog open :
var select2List=syncToLoadTheData();//data for select2
$('#search-user-select').select2({ //here when secondly executed, the select2's data on UI does not refreshed
data:select2List,
matcher: function(params, data){
var key = params.term;
if ($.trim(key) === '') {
return data;
}
if( (matchKeyAndPinyin(key,data.text))){
return data;
}
return null;
}
}
But the problem is even though the list is changing, the select options does not change at all.Please note in my test case, every time i open the dialog, the data from server is changed:
What I had tried:
1.when init:
data: function() { return {results: select2List}; }// not work to show any data at all
2.when secondly open dialog:
$( "#search-user-select").select2('data',newdata,true);//not work to have the new data
3.when secondly open:
$("#search-user-select").select2("updateResults");//Error, does not have this method
And some other method like directly change the array's data(only one copy of the data), but none of them work.
I had the same problem before, my problem was i need to update the select2 after every ajax request with new data.
and this how i fixed my code.
EventId = $(this).attr('id');
$.ajax({
url: 'AjaxGetAllEventPerons',
type: 'POST',
dataType: 'json',
data: {id: EventId},
})
.done(function(data) {
$("#select2_job").select2({
minimumInputLength: 2,
multiple:true,
initSelection : function (element, callback) {
//var data = data;
callback(data);
},
ajax: {
url: "/AjaxGetAllPersonForEvent",
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.fullname
});
});
return {
results: myResults
};
}
}
});
I hope this example will help you to solve your problem

Can not seem to pass more than one variable with jquery to mysql

I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....

Loading remote data only once with Select2

As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>

Access class variable in jquery

I have a select in my html and would like to add the options via ajax when the page loads. The options values are in my DB and I get them via a call to ajax. To do so, I'm writing a class in javascript but I just can't get my data when it runs. Please take a look :
--- Main.js ---
function MyLoader() {
this._clients = null;
this._code = null;
}
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
}
});
},
getCode: function() {...}
};
Then I have the following :
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
alert(loader._clients);
//Here I want to add my options to the select
});
My alert always returns null, and I don't understand why. I need to save my data in the class in order to access them anytime I need to.
Can you point me to the right direction to make all my stuff work ? Thank you for your answers.
Loader.prototype = { // v---callback parameter
loadClients: function(callback) {
$.ajax({
url: "my/php/",
context: this, // <---set success context
type: "POST",
data: {...},
success: callback // <---pass callback
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
// v---pass callback
loader.loadClients(function(response) {
this._clients = response;
alert(this._clients);
//Here I want to add my options to the select
});
});
I believe that you need to do all of your dynamic loading inside of your 'success' callback, since it is loading asynchronously.
You need to do it inside the success callback since it's async:
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
alert(loader._clients);
//Here I want to add my options to the select
}
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
});

Categories