How to send JSON value to tui calendar using ajax - php

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);
});

Related

Remove previous data when executing AJAX request multiple times using ajax

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);
});

Laravel: DataTable Multiple checkboxes

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.

Ajax request showing error message while successfull updation laravel

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>

Looking for a Solution of "Live Search In php & storing back selected result in MYSQL dB"

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;

How to set Ajax URL dynamically?

I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension

Categories