Fullcalendar v4 refetch only one single event - javascript

I'm trying to figure out the proper way to refetch one single event (when I add an event and when I update an event)
I'm currently using calendar.refetchEvents(); which will refetch all the events after adding/updating an event but it would be better if I could only refetch that single event.
I use events as a function like so
eventSources: [
{
events:function(fetchinfo, successCallback, failureCallback) {
$.ajax({
type:'GET',
url: '/rdv/data',
data:{
start:moment(fetchinfo.start).format('YYYY-MM-DD HH:mm'),
end:moment(fetchinfo.end).format('YYYY-MM-DD HH:mm'),
},
success: function(data) {
let arrayEvents = [];
$.each(data, function (key) {
arrayEvents.push( {
title: "title",
start: data[key].date_debut_rdv,
end: data[key].date_fin_rdv,
extendedProps: {
id: data[key].id,
nom_client: data[key].animal.client.nom_client,
prenom_client: data[key].animal.client.prenom_client,
id_client: data[key].animal.client.id,
nom_animal: data[key].animal.nom_animal,
},
});
});
successCallback(arrayEvents);
},
error: function(data){
//
}
})
}
}
]
Add an event inside a dateClick
$.ajax({
type: "POST",
url: "/rdvs/ajoutRdv",
data: {
_token: "{{ csrf_token() }}",
client_id: client_id,
animal_id: animal_id,
date_debut_rdv: date_debut_rdv,
statut_rdv_id: statut_rdv_id,
prestations: prestations,
tvas: tvas,
supplements: supplements,
},
success: function () {
calendar.refetchEvents();
$('#modalEditRdv').modal('hide');
},
error: function(data) {
//
});
}
})
Update an event inside an eventClick
$.ajax({
type: "POST",
url: "/rdvs/click/"+id,
data: {
_token: "{{ csrf_token() }}",
rdv_id: event.event.extendedProps.id,
client_id: client_id,
animal_id: animal_id,
date_debut_rdv: date_debut_rdv,
statut_rdv_id: statut_rdv_id,
prestations: prestations,
tvas: tvas,
supplements: supplements,
},
success: function (data) {
calendar.refetchEvents();
//I could do something like this without making a request to the server
//but is there another way ?
//event.event.setExtendedProp("nom_animal", data[0].nom_animal);
//event.event.setStart(data[1]);
//event.event.setEnd(data[2]);
$('#modalEditRdv').modal('hide');
},
error: function(data) {
//
}
})
I see there is EventSource::refetch but it would refetch all the events as well if I'm correct ?
A little help would be very appreciated,
Thank you !

Related

Only with a double click does the event occur

button Uptade
<button type="button" id="custom-icon" onclick="UpdateParents()"">Update</button>
function AJAX
function UpdateParents() {
var ParentsOBJ = { IDkids: $("#IDkids").val(), NameKids: $("#NameKids").val(), LastNameKids: $("#LastNameKids1").val(), NameFather: $("#NameFather").val(), NameMother: $("#NameMother").val(), PhoneMother: $("#PhoneMother").val(), PhoneFather: $("#PhoneFather").val() };
$.ajax({
type: "PUT",
url: "/api/Parents/" + ParentsOBJ.IDkids,
data: JSON.stringify(ParentsOBJ),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Parents = JSON.parse(data);
$('#custom-icon').on('click',function () {
swal({ title: "update", text: "ok.", icon: "/up.jpg" });
setTimeout(function () {
location.reload();
}, 2000);
});
},
failure: function (errMsg) {
alert(errMsg);
}
});
$('#custom-icon').on('click',function ()
Only when I double-click the button does the operation take place.
I can understand why this is happening (click in click),
But can't solve the problem.
I will be happy to resolve!!!
The problem is that you double bind the $('#custom-icon'), and the 2nd bind takes place inside an ajax success callback, which takes in place only after the ajax request that has been triggered from the first click has been finished.
All you need to do is to remove the 2nd binding, as it's unnecessary because you already bind the click event from the html, your new code will look like this:
function UpdateParents() {
var ParentsOBJ = { IDkids: $("#IDkids").val(), NameKids: $("#NameKids").val(), LastNameKids: $("#LastNameKids1").val(), NameFather: $("#NameFather").val(), NameMother: $("#NameMother").val(), PhoneMother: $("#PhoneMother").val(), PhoneFather: $("#PhoneFather").val() };
$.ajax({
type: "PUT",
url: "/api/Parents/" + ParentsOBJ.IDkids,
data: JSON.stringify(ParentsOBJ),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Parents = JSON.parse(data);
swal({ title: "update", text: "ok.", icon: "/up.jpg" });
setTimeout(function () {
location.reload();
}, 2000);
},
failure: function (errMsg) {
alert(errMsg);
}
});
A better practice here would be to accept a callback method from the UpdateParents function, and then pass the success as a callback.

How to return the 2nd data variable of an $.ajax() function?

Here's my ajax function. How do I console.log the first data variable? The below code doesn't work:
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function() {
console.log(text)
}
})
})
However when I do this:
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data:
$('.comment_text').serialize(),
success: function(data) {
console.log(data)
}
})
})
it works fine. Any idea why?
Because
success: function() {
console.log(text)
}
text doesn't exist in this context.
this.data.text would work because you're inside a method of your object:
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function() {
console.log(this.data.text);
// everything from the object is accessible with this here (i.e. type and data fields)
}
})
try to get the data you want to send to an external variable so you will have access to its properties inside the ajax success callback function.
$('.comment_form').on('submit', function(e) {
var _data = {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
e.preventDefault();
$.ajax({
type: 'POST',
data: _data,
success: function() {
console.log(_data.text)
}
})
})
console.log($('.comment_text').val())
Your second example is working because it's logging the parameter dataof the success callback function, aka the response from the server.
$('.comment_form').on('submit', function(e) {
e.preventDefault();
var dataToSend = {
text: $('.comment_text').serialize(),
csrfmiddlewaretoken: '{{ csrf_token }}',
};
$.ajax({
type: 'POST',
data: dataToSend,
success: function() {
console.log(dataToSend.text)
}
})
})
Case 1:
If you just want to access the same text what you are sending in ajax data hit then you have to initialize it first. Because text is not any variable here so far so it will give undefined. You can do it like:
$('.comment_form').on('submit', function(e) {
var requestData = {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
e.preventDefault();
$.ajax({
type: 'POST',
data: requestData ,
success: function() {
console.log(requestData.text)
}
})
})
Case 2: If you are trying to access the text from ajax response then you have to pass the same parameter in success function.
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(text) {
console.log(text)
}
})
})
Well if you want to serialize and want some data to be sent along the way.
Here is what I do:
var myForm = document.getElementById('myForm');
formData = new FormData(myForm);
formData.append('custom_key', 'CUSTOM VALUE');
...
Then in AJAX data:
$.ajax({
...
data : formData,
...
});
Now in the backend code you can find your form fields as well as your custom key value.
Hope this helps.

cannot post data to php from jquery's form

I want to post form's data to php after the user submit.
The question is that the form is created by jquery in ajax.
The form creating looks like:
$.ajax({
type: "POST",
url: "myphp.php",
data: {label: label},
success: function(result) {
for (i = 0; i<result.item.length; i++){
var itemData= result.item[i].itemData;
var div = $("<div class ='detail'></div>");
// the form will not be displayed, until the parent div has been clicked.
var form = $("<form/>", {// create the form
class: 'itemClass',
id: 'itemId',
method: 'POST'
}).append(
// Create <form> Tag and Appending in Div .detail.
$("<p/>").text("item:"),$("<br/>"),
$("<input/>", {
type: 'text',
id: 'itemData',
name: 'itemData',
value: itemData
}),
$("<br/>"),
$("<input/>", {
type: 'submit',
id: 'submit',
value: 'Submit'
}))
div.append(form);
$("#htmlDiv").append(div);
}
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
});
However, the submitting code is fail. It is not been executing.
$("#itemId").submit(function(e) {
e.preventDefault();
var itemData= $('#itemData').val();
$.ajax({
type: "POST",
url: "target.php",
data: {itemData: itemData},
success: function(result) {
alert(result); //It return a string
},
dataType: "text",
error: function(xhr){
console.log("error");
}
});
Any idea? Why the submitting can not be used?
Use event-delegation as by the time events are attached($("#itemId").submit(function(e){...), target element($("#itemId")) is not present in the DOM
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Try this:
$('#htmlDiv').on('submit', '#itemId', function(e) {
e.preventDefault();
var itemData = $('#itemData').val();
$.ajax({
type: "POST",
url: "target.php",
data: {
itemData: itemData
},
success: function(result) {
alert(result); //It return a string
},
dataType: "text",
error: function(xhr) {
console.log("error");
}
});
});

Unable to process binding, push JSON data to ObservableArray using ko.mapping.fromJS

Can anybody explain what's wrong in my code, I am new to knockout... So, initially I receive json data from database and it works. Than when I click 'Add some' I want to add(push) same data from database to my observable array. The code below obviously doesn't work. Thanks.
Error: Unable to process binding "text: function (){return AdId }"...
HTML:
<div data-bind="foreach: Ads">
<p data-bind="text: AdId"></p>
</div>
<div data-bind="click: addSome">Add some</div>
MODEL:
function AdListModel() {
var self = this;
self.Ads = ko.mapping.fromJS([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
self.InitialData = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.result(data); <---- works
}
});
}
self.addSome = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(data); <---- doesn't work
},
});
};
self.InitialData();
}
ko.applyBindings(new AdListModel());
I tried self.Ads.push(ko.mapping.fromJS(data)) - didn't work.
It seems from the error message, that your model does not have an AdId property.
Can you add a dump of the JSON model returned by your API?
Edit
Your Ads property should be an ko.observableArray() instead of ko.mapping.fromJS([]):
function AdListModel() {
var self = this;
self.Ads = ko.observableArray([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
Edit 2
And you have to map the data before pushing it:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(ko.mapping.fromJS(data));
},
});
Edit 3
If your JSON looks like this:
[
{"AdId":1,"AdContent":"test1"},
{"AdId":2,"AdContent":"test2"}
]
Then it is an Array and you have to iterate over each entries:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
data.forEach(function(d) {
self.Ads.push(ko.mapping.fromJS(d));
});
},
});

prevent onchange event in jquery

I am using knockout with MVC in my project. when I pass viewModel on dropdown change It's getting continues ajax request to the server. How can I avoid the continues request??? any one can please help me on this???
My View
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width", #id = "rmch" }, "Text", "Value").Value(m=>m.NoOfRooms)
Javascript
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})
if I remove value part from the dropdownlist in the view It's working .but I need the value for the processing.
The simplest thing I can think of is to set the dropdownlist to readonly before updating it, then when you have finished adding the new items, remove the readonly attribute.
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//this will disable the onchange event
$('#rmch').attr("readonly","readonly");
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
//this will enable the onchange event for the next time you select something.
$('#rmch').removeAttr("readonly");
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})

Categories

Resources