I am using Toast tui calendar https://nhn.github.io/tui.calendar/latest/ and I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response. please help me how can i resolve that thank u.
I think that there is something that I've missed.
BookingController
public function getBookingSlot(Request $request){
$userBookings = Booking::where('room_id',$request->room_id)->where('booking_status',1)->get();
foreach($userBookings as $booking){
$events [] = [
'id' => $booking->id,
'calendarId' => $booking->id,
'title' => 'Booked',
'category' => 'time',
'dueDateClass' => '',
'start' => $booking->start_datetime,
'end' => $booking->end_datetime,
];
}
return \Response::json([
'events' => $events ?? null
]);
}
Html view
<div class="card mb-5 ">
<div id="calendar" style="height: 800px;"></div>
</div>
Script
<script type="text/javascript">
var Calendar = tui.Calendar;
var calendar = new Calendar('#calendar', {
defaultView: 'month',
taskView: false,
useCreationPopup: false,
useDetailPopup: true,
allDaySlot: false,
droppable: false,
template: {
monthDayname: function(dayname) {
return '<span class="calendar-week-dayname-name">' + dayname.label + '</span>';
}
}
});
document.getElementById('my-today-button').addEventListener('click', function() {
calendar.today();
});
document.getElementById('my-next-button').addEventListener('click', function() {
calendar.next();
});
document.getElementById('my-prev-button').addEventListener('click', function() {
calendar.prev();
});
document.getElementById('weekView').addEventListener('click', function() {
calendar.changeView('week', true);
});
document.getElementById('monthView').addEventListener('click', function() {
calendar.changeView('month', true);
});
$(".butonSubmit").click(function(){
let room_id = $(".carousel-item.active .room_id").val();
$.ajax({
url: "{{route('get-booking-slot')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
room_id:room_id,
},
success:function(response){
calendar.createSchedules(
result = JSON.parse(JSON.stringify(response.events))
);
console.log(result);
},
error: function(response) {
console.log(error);
},
});
});
calendar.on('beforeUpdateSchedule', function(event) {
var schedule = event.schedule;
var changes = event.changes;
calendar.updateSchedule(schedule.id, schedule.calendarId, changes);
});
Related
I am using Tui calendar https://ui.toast.com/tui-calendar and i have already get booking date related to room id in ajax response but i want to send json value to tui calendar using ajax response i don't know how can i show json data inside calendar please help me how can i resolve that ? thank u.
please check error
https://flareapp.io/share/bP9YaMMP
BookingController
public function getBookingSlot(Request $request){
$userBookings = Booking::where('room_id',$request->room_id)-
>where('booking_status',1)-
>get();
foreach($userBookings as $booking){
$events [] = [
'id' => $booking->id,
'calendarId' => $booking->id,
'title' => 'Booked',
'category' => 'time',
'dueDateClass' => '',
'start' => $booking->start_datetime,
'end' => $booking->end_datetime,
];
}
return \Response::json([
'events' => $events
]);
}
script
var Calendar = tui.Calendar;
var calendar = new Calendar('#calendar', {
defaultView: 'month',
taskView: false,
useCreationPopup: false,
useDetailPopup: true,
allDaySlot: false,
droppable: false,
template: {
monthDayname: function(dayname) {
return '<span class="calendar-week-dayname-name">' + dayname.label + '</span>';
}
}
});
document.getElementById('my-today-button').addEventListener('click', function() {
calendar.today();
});
document.getElementById('my-next-button').addEventListener('click', function() {
calendar.next();
});
document.getElementById('my-prev-button').addEventListener('click', function() {
calendar.prev();
});
document.getElementById('weekView').addEventListener('click', function() {
calendar.changeView('week', true);
});
document.getElementById('monthView').addEventListener('click', function() {
calendar.changeView('month', true);
});
$(".butonSubmit").click(function(){
let room_id = $(".carousel-item.active .room_id").val();
$.ajax({
url: "{{route('get-booking-slot')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
room_id:room_id,
},
success:function(response){
var $bookingUser = #json($events);
},
error: function(response) {
console.log(error);
},
});
});
calendar.createSchedules(
events= $bookingUser
);
calendar.on('beforeUpdateSchedule', function(event) {
var schedule = event.schedule;
var changes = event.changes;
calendar.updateSchedule(schedule.id, schedule.calendarId, changes);
});
Im fetching my data in my server side and I put checkbox.
I need some clarification, do I need to put checkbox here or it will be automatically added?
Controller
$result[] = array(
'#' => '<span style="font-size: 12px; color: gray">'.$counter++.'</span>',
'number' => '<p>'.$value->number.'</p>',
'vendor' => '<p>'.$vendor->name .'</p>',
'document_reference' => '<p>'.$value->document_reference.'</p>',
'date_needed' => '<p>'.$value->date_needed.'</p>',
'requesting_department' => '<p>'.$department->name.'</p>',
'amount' => '<p align="right">'.number_format($value->total_amount,2).'</p>',
'status' => '<p>'.$status.'</p>',
'approval_status' => '<p id="'.$value->id.'">'.$approval.'</p>',
'created_by' => '<p id="created_at'.$value->id.'">'.$user->name.'</p>',
'action' => '<i class="fa fa-eye"></i>',
'checkbox' => '<input type="checkbox" name="checkbox[]" value="'.$value->id.'">'
In my view page I used route to call this method. In here I have now my data.
My View
var table3 = $('#get-rfp-for-approval-table').DataTable({
'processing': true,
'serverSide': true,
ajax: {
url: '/requests/request-for-payment/getRFPforApproval',
dataSrc: ''
},
columns: [
{ data: '#' },
{ data: 'number' },
{ data: 'vendor' },
{ data: 'document_reference' },
{ data: 'date_needed' },
{ data: 'requesting_department' },
{ data: 'amount' },
{ data: 'status' },
{ data: 'created_by' },
{ data: 'approval_status' },
{ data: 'action' },
{ data: 'checkbox' },
],
columnDefs: [
{
targets: 11,
checkboxes: {
selectRow: true
}
}
],
select: {
style: 'multi'
},
order: [[1,'desc']]
});
Example I have 15 data, I checked data 5 and data 14. then I submit the form.
My form
if ( $('#approved-selected-form').length > 0 ) {
$('#approved-selected-form').submit(function(e){
var form = this;
var rows_selected = table3.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'checkbox[]')
.val(rowId)
);
});
var formData = $(this).serialize();
swal({
title: "Are you sure?",
text: "Transaction will be approved.",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willSave) => {
if (willSave) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/requests/request-for-payment/approvedTransaction',
type: "POST",
data: formData,
beforeSend: function() {
var span = document.createElement("span");
span.innerHTML = '<span class="loading-animation">LOADING...</span>';
swal({
content: span,
icon: "warning",
buttons: false,
closeOnClickOutside: false
});
$('.request-for-payment-finish').attr('disabled', 'disabled');
},
success: function(response) {
if (response != '') {
$('#get-request-for-payment-table').DataTable().destroy();
getRequestForPaymentTable();
$('#add-request-for-payment-form').trigger("reset");
swal("Transaction has been saved!", {
icon: "success",
});
setTimeout(
function()
{
window.location.href = "/requests/request-for-payment?id="+response+"#view-request-for-payment-modal";
}, 1500);
}
},
complete: function() {
$('.request-for-payment-finish').removeAttr('disabled');
}
});
} else {
swal("Save Aborted");
}
});
e.preventDefault();
return false;
})
}
NOTE: I tried to dd it in my controller it gives me this
array:1 [
"get-rfp-for-approval-table_length" => "10"
]
I also noticed that in my th, I dont have checkbox(when I clicked this, everything will be checked). Im using this as a guide. https://jsfiddle.net/snqw56dw/3182/.
Question: How can I get those values in my controller?
You should be returning ID in your controller.
$result[] = array(
// ... skipped ...
'checkbox' => $value->id
);
Also since checkbox in column with index 11, you should be using that index when retrieving the data.
var rows_selected = table3.column(11).checkboxes.selected();
On the side note, I see that you're using server-side processing mode ('serverSide': true). Make sure your controller returns proper response.
I'm coding a simple comment section on my project and from now it's working pretty good except at the moment of edit or delete a fresh new comment. I can create, edit and delete all the comments using ajax but to delete or edit a new comment i have to refresh the page. Reason? Trying to get property of non object. Looks like i can't get the comment id of new comments, to get those id's i have to refresh the page..
This is my ajax.
Create a new comment:
$('.send').click(function(e){
e.preventDefault();
var dataSerialize = $('#add-comment').serialize();
var $btn = $(this).button('loading');
$.ajax({
method: 'post',
url: urlPostComment,
data: dataSerialize,
dataType: 'json',
success: function (data) {
console.log(data);
if( data.success )
{
$('#post-comments').append(
"<section class='comment-list"+data.id+"'><article class='row'><div class='col-md-3 col-sm-3 hidden-xs'><figure class='thumbnail'><img class='img-responsive' src='/uploads/avatars/"+data.picture+"' /></figure></div><div class='col-md-8 col-sm-8'><div class='panel panel-default arrow left'><div class='panel-body'><header class='text-left'><div class='comment-user'><i class='fa fa-user'></i> "+data.name+" "+data.lastname+" <time class='comment-date p-l-10'><i class='fa fa-clock-o'></i> "+data.timestamp+"</time></div></header><div id='comment-post' data-commentid='"+data.id+"'><p id='display-comment' class='store-comment p-t-10'>"+data.comment+"</p></div></div><div class='panel-footer list-inline comment-footer'><a href='#' data-toggle='modal' data-target='edit-comment' class='edit-comment' data-id='"+data.id+"' data-name='"+data.comment+"'>Editar</a> <a href='#' data-toggle='modal' data-target='delete-comment'class='delete-comment' data-id='"+data.id+"' data-name='"+data.comment+"'>Eliminar</a></div></div></div></article></section>"
);
toastr.success('Comment created.', '', {timeOut: 7000})
$('#comment-new').val('');
}
else {
toastr.warning(" "+ data.message +" ", '', {timeOut: 7000})
}
},
error: function () {
toastr.warning('Message couldn't be sent, Try again.', '', {timeOut: 7000})
},
complete: function () {
$btn.button('reset');
}
});
});
My update Ajax:
var commentId = 0;
var divcomment = null;
$('body').on('click', '.edit-comment', function(event){
event.preventDefault();
divcomment = this.parentNode.parentNode;
commentId = $("#comment-post",event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
});
$('body').on('click', '#modal-save', function(){
var $btn = $(this).button('loading');
var comment = $('#comment').val();
$(this).button('loading');
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: comment,
commentId: commentId,
_token: token,
_method: 'PUT',
},
dataType: 'json'
})
.done(function (msg){
if (msg.success === true) {
$(divcomment).find('#display-comment').text(comment);
}
$btn.button('reset');
$('#edit-comment').modal('hide');
toastr.success('Comentario editado.', '', {timeOut: 7000})
});
});
And my Delete Ajax code:
$('body').on('click', '.delete-comment', function(){
$('#delete-comment').modal();
$('#comment-value').text($(this).data('id'));
});
$('body').on('click', '#comment-delete', function(e){
e.preventDefault();
var $btn = $(this).button('loading');
$(this).button('loading');
$.ajax({
type: 'delete',
url: urlDelete,
data:{
'id': $('#comment-value').text(),
'_method': 'delete',
'_token': token
}
})
.done(function(response){
$('.comment-list' + $('#comment-value').text()).remove();
$('#delete-comment').modal('hide');
toastr.success(" "+response.success+" ", '', {timeOut: 7000})
$btn.button('reset');
})
.fail(function(){
$btn.button('reset');
$('#delete-comment').modal('hide');
toastr.warning('Message couldn't be sent, try again.', '', {timeOut:
7000})
})
});
UPDATE:
Variables:
var token = '{{ Session::token() }}';
var urlPostComment = '{{ url('comments/' .$post->id) }}';
var urlEdit = '{{ url('comments/update') }}';
var urlDelete = '{{ url('comments/' .$comment->id) }}';
About this last one var urlDelete = '{{ url('comments/' .$comment->id) }}'; i don't know why if post doesn't have a comment it gaves me an error "undefined variable id" or "undefined variable comment"
Controller Logic:
public function store(Request $request, $post_id)
{
if(!$request->has('comment') || empty($request->comment))
{
return response()->json([
'message' => 'No puedes enviar un comentario vacĂo.',
'success' => false
]);
}
$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->user->profilepic = $comment->user->profilepic;
$comment->post_id = $post_id;
$comment->save();
return response()->json([
'comment' => $comment->comment,
'user_id' => $comment->user_id,
'post_id' => $comment->post_id,
'picture' => $comment->user->profilepic,
'name' => $comment->user->name,
'lastname' => $comment->user->last_name,
'timestamp' => $comment->created_at->diffForHumans(),
'post_slug' => $post->slug,
'success' => true
]);
}
public function update(Request $request)
{
$this->validate($request, [
'comment' => 'required'
]);
$comment = Comment::find($request['commentId']);
if (Auth::user() != $comment->user) {
return response()->json([
'errorupdate' => 'No hemos podido actualizar tu comentario, intenta nuevamente',
'success' => false], 200);
}
$comment->comment = $request['comment'];
$comment->save();
return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}
public function destroy(Request $req)
{
$response = [];
$comment = new Comment;
$comment = Comment::find($req->id);
if (Auth::user() != $comment->user) {
return redirect()->back();
}
if ($comment->delete()) {
$response['success'] = 'Comentario eliminado.';
$response['subject'] = $comment;
}
return response()->json($response);
}
In the laravel update form The code for controller is:
public function edit(){
$inputValue = [
'id' => Input::get('id'),
'name' => Input::get('name'),
'parent_id' => Input::get('parent_id'),
'color' => Input::get('color'),
'description' => Input::get('notes')
];
$validator = \Validator::make( $inputValue, \Resource::getEditFolderRules() );
// Validate the input and return correct response
if ($validator->fails()){
return Response::json([
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
]);
}
$resource = $this->repo->updateFolderBasicDetail($inputValue);
return Response::json([
'success' => true,
'url' => \URL::route('folder-detail', $inputValue['id'])
]);
}
and js is:
<script type="text/javascript">
$(function(){
$("#edit-folder").on('submit', function(e){
e.preventDefault();
if($("#edit-folder").valid() == true){
var description = CKEDITOR.instances.edit_folder_ckeditor1.getData();
$('#notes').val(description);
$.ajax({
url: "{{ URL::to('folder/edit') }}",
type: "POST",
data: $( this ).serialize(),
dataType: "json",
success:function(data) {
var errorString = '<ul class="msg msg_unsuccess">';
var success = 'Folder is updated.';
errorString += '<li>' + success + '</li>';
errorString += '</ul>';
$('#sucessmsg').html(errorString).delay(3000).fadeOut();
$('.modal-content').delay(3000).fadeOut();
$('.fade').delay(3000).fadeOut();
},
error:function(data) {
var errorString = '<ul class="msg msg_success">';
var error = 'Folder is not updated.';
errorString += '<li>' + error + '</li>';
errorString += '</ul>';
$('#sucessmsg').html(errorString).delay(3000).fadeOut();
$('.modal-content').delay(3000).fadeOut();
$('.fade').delay(3000).fadeOut();
setTimeout(function(){location.reload();},3000);
}
});
}
});
});
</script>
but when I update the folder it is updating and message is displaying from error:function.
don't understand where I am wrong Please help me out.
I use AJAX in Laravel 5.2 with routes, created variable url and variable token(if need), in php file where views, before included script
<script>
var token = '{{ Session::token()}}';
var url = '{{ route('select_cafe') }}';
</script>
<script src="{{asset('/script/select_cafe.js')}}" ></script>
I am trying to solve the following problem. I want to create a live search in PHP, retrieving Values from a dB, and storing back multiple selected values in a SQL table.
Many sites I visit today like this, but no perfect solution found.
<input name="find" id="find" value=""/>
<ul class="selectedItems"></ul>
$("#luogoNascita").autocomplete({
minLength: 3,
dataType: "json",
source: function(req, add){
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
data: { find : $("#find").val() } ,
success: function(data){
if(data.result){
add(data.result);
}
else{
$(this).val('');
}
}
});
},
select: function( event, ui ) {
if(ui.item)
{
var obj = $.parseJSON(ui.item.value);
}
else{
$(this).val('');
}
},
close: function(event, ui) {
var obj = jQuery.parseJSON($( this ).val()) || {};
var id = obj.id || null;
if (id){
$( this ).val(obj.selected);
$.post(saveUrl,{id: id},function(res){
console.log(res);
}) ;
}
$('.selectedItems')
.append('<li>'+obj.selected+'</li>');
$(this).val(''); // clear input
}
});
//server side PHP // url.php
$data['result'] = array();
$data['result'][] = array(
'label'=> 'First',
'value'=> json_encode(array(
'id' => 1,
'selected' => 'First'
))
);
$data['result'][] = array(
'label'=> 'Second',
'value'=> json_encode(array(
'id' => 2,
'selected' => 'Second'
))
);
echo json_encode($data);
// server side PHP // saveUrl.php
$_POST['id'];
//save in DB function;