I am using FullCalendar in laravel 8 project and I use it to display all the events from the database.
This is the code:
My controller
public function index(Request $request, $id) {
$patient = [];
$listOfPatients = [];
$appointments = [];
//apply permission constraits
$patient = Patient::find($id);
$listOfPatients = Patient::all();
$appointments = appointments::all();
$this->authorize('view', $patient);
// $appointments = $patient->remarks()->get()->sortBy([['id', 'desc']]);
if($request->ajax()) {
$data = appointments::whereDate('start', '>=', $request->start)
->whereDate('end', '<=', $request->end)
->get(['id', 'title', 'description', 'start', 'end']);
return response()->json($data);
}
return view('patient.appointments', [ "appointments" => $appointments, "patient" => $patient, "listOfPatients" => $listOfPatients]);
}
My js
$(document).ready(function () {
var SITEURL = "{{ url('/') }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full_calendar_events').fullCalendar({
editable: false,
editable: false,
eventSources: [
{
url: '/{id}/appointments',
color: '#65a9d7', // an option!
textColor: '#3c3d3d' // an option!
}
],
});
});
I also got this error:
jquery.min.js:4 GET http://127.0.0.1:8000/%7Bid%7D/appointments?start=2022-02-27&end=2022-04-10&_=1648373948124 404 (Not Found)
Related
I setup future payment in my laravel app with stripe. However, after following stripe integration from stripe official doc I encountered this error response.
Here's my script:
<script>
var stripeSetupIntent = function (stripe, setupIntent) {
const email = document.getElementById("stripe-email").value;
stripe.confirmCardSetup(setupIntent.client_secret,
{
payment_method: {
card: card,
billing_details: {
name: email,
},
},
}
).then(function(result) {
if (result.error) {
// Display error.message in your UI.
console.log('Error: ', result.error)
// var displayError = document.getElementById("card-errors");
// displayError.textContent = result.error.message;
} else {
console.log('Sucess')
// The setup has succeeded. Display a success message.
}
});
};
var getSetupIntent = function(stripe) {
axios.post('/api/createcustomerinstripe').then(function (response) {
console.log('getSetupIntent: ', response.data.setupIntent)
stripeSetupIntent(stripe, response.data.setupIntent)
})
};
$(document).ready(function () {
let stripe = null;
//get stripe public key
axios.get('/api/stripe-key').then(function (response) {
stripe = Stripe(response.data.publicKey);
const elements = stripe.elements();
const card = elements.create('card');
card.mount('#card-element');
})
var button = document.getElementById("savecard");
button.addEventListener("click", function(event) {
event.preventDefault();
// changeLoadingState(true);
getSetupIntent(stripe)
});
})
</script>
Backend code:
Controller:
public function getStripeKey()
{
$publicKey = env('STRIPE_KEY');
$data = [
'message' => 'Stripe key successfully retrieved.',
'publicKey' => $publicKey
];
return response()->json($data, 200, [], JSON_PRETTY_PRINT);
}
public function CreateCustomerInStripe()
{
Stripe::setApiKey(env('STRIPE_SECRET'));
$customer = Customer::create([
'email' => auth()->user()->email
]);
$setupIntent = SetupIntent::create([
'customer' => $customer->id
]);
$data = [
'message' => 'A new SetupIntent was created.',
'setupIntent' => $setupIntent
];
return response()->json($data, 200, [], JSON_PRETTY_PRINT);
}
Backend code web:
Route::get('stripe-key', 'api\StripePaymentController#getStripeKey')->name('stripe.key');
Route::post('createcustomerinstripe', 'api\StripePaymentController#CreateCustomerInStripe')->name('createcustomerinstripe');
I use the stripe documentation here https://stripe.com/docs/payments/save-and-reuse#web-test-integration
stripe version:
<script src="https://js.stripe.com/v3/"></script>
laravel version:
https://laravel.com/docs/7.x/billing
i am new at laravel ,when i enable switch popup message is working perfectly but I don't want to show error popup message when i disable to switch please how can i do that help me thanks.
Does Anyone have an idea please help me thank.
CONTROLLER
public function featured(Request $request)
{
if ($request->is_featured) {
$assignFeature = Product::where('is_featured', 1)->exists();
if ($assignFeature) {
$response['error'] = 'Product is already featured';
return response()->json($response, 422);
}
}
$id = $request->input('id');
$featured = $request->input('is_featured');
$featurediItem = Product::find($id);
if ($featurediItem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
you can use axios.post.then method to work after getting response success fully. Something like this
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
}
here you can use your response variable to check if is_featured true do something what you want
I have the following script in the blade.php:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var SITEURL = "{{url('/dash')}}";
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'bootstrap', 'interaction', 'dayGrid', 'timeGrid'],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,'
},
themeSystem: 'bootstrap',
editable: true,
navLinks: true,
events: SITEURL + "/calendar",
displayEventTime: true,
defaultView: 'timeGridWeek',
selectable: true,
selectHelper: true,
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
And in the controller this part which is get the events from the database:
public function index(Request $request)
{
if(request()->ajax()) {
$returnedColumns = ['id', 'title', 'start', 'end'];
$start = (!empty($request->start)) ? ($request->start) : ('');
$end = (!empty($request->end)) ? ($request->end) : ('');
$events = Event::whereBetween('start', [$start, $end])->get($returnedColumns);
return response()->json($events);
}
return view('/dash/calendar');
}
The Json looks like this, if I remove the if(request()->ajax()) { part:
[{"id":347,"title":"Unavailable","start":"2020-02-11 06:00:00","end":"2020-02-11 06:30:00"}]
Seems the request working fine, but I got JSON parse error, and the calendar just won't show the events. What could be a problem?
I'm trying to download an excel file using ajax method in laravel.
Controller function:
$myFile = Excel::create($name, function ($excel) use ($export) {
$excel->sheet('Data', function ($sheet) use ($export) {
$sheet->fromArray($export);
$sheet->cells('A1:N1', function ($cells) {
$cells->setBackground('#dbdbdb');
$cells->setFontColor('#000000');
$cells->setFontWeight('bold');
$cells->setFont(array(
'family' => 'Calibri',
'size' => '9',
));
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 9,
),
));
});
});
$myFile = $myFile->string('xlsx');
$response = array(
'name' => $name,
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile),
);
return response()->json($response);
Ajax function:
$(document).on('click', '.ExportJobs', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var ids = [];
$(".InvoiceCheckBox:checked").each(function(e) {
ids.push(this.value);
});
data = {
"ids": ids,
};
$.ajax({
method: "POST",
url: "/exportNew",
data: data,
success: function(response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
}
});
});
But using above controller method is not returning excel formatted file if I change string value from xlsx to csv then csv formatted file is getting downloaded.
How do we make the excel formatted file downloaded? Any suggestions, Please!
I know this is quite late, but posting for others who struggle with same issue like me
I also needed to download excel from using Maatwebsite excel library by using ajax post call.
added a button to fire the ajax call to download excel file
<button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
Download
</button>
Used following js code to post ajax request
function downloadExcel() {
var salaryMonth = $("#dp-salary-month").datepicker("getDate");
var department = $("#cbox-department");
var month = new Date(salaryMonth).getMonth() + 1;
var year = new Date(salaryMonth).getFullYear();
$.ajax({
xhrFields: {
responseType: 'blob',
},
type: 'POST',
url: '/downloadPayroll',
data: {
salaryMonth: month,
salaryYear: year,
is_employee_salary: 1,
department: department.val()
},
success: function(result, status, xhr) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
// The actual download
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
in routes/web.php file set the reoute for my controller
Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController#downloadPayroll');
Here I used maatwebsite/excel library to generate excel file with FromQuery approach but due to library update Excel::create has been replaced by Excel::download in "maatwebsite/excel": "^3.1" I used download method in my case here is my HelperClass to generate records according to my requirement
PayrollHelper.php
namespace App\Http\Helpers;
use App\PayrollEmployee;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class PayrollHelper implements FromQuery
{
use Exportable;
public function forDepartment(int $department)
{
$this->department = $department;
return $this;
}
public function forMonth(string $month)
{
$this->month = $month;
return $this;
}
public function query()
{
// get the salary information for the given month and given department
return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]);
}
}
finally in my controller
class PayrollController extends Controller
{
public function downloadPayroll(Request $request)
{
$file_name = '';
try {
$requestData = $request->all();
$salary_month = $requestData['salaryMonth'];
$salary_year = $requestData['salaryYear'];
$department = $requestData['department'];
$is_employee_salary = boolval($requestData['is_employee_salary']);
$month = Carbon::createFromDate($salary_year, $salary_month);
$month_start = Carbon::parse($month)->startOfMonth();
$formated_month = Carbon::parse($month)->format('F Y');
$file_name = 'Employee_salary_' . $formated_month . '.xlsx';
// to download directly need to return file
return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
} catch (exception $e) {
}
}
}
After creating excel file return file to get as ajax response as blob
That's all
Just see the xhrFields to set responseType as blob and then see the ajax success part. Hope you everyone find the solution:
<script>
$(document).ready(function(){
$("#ExportData").click(function()
{
dataCaptureExport();
});
});
function dataCaptureExport(){
var FromDate = $('#dateFrom').val();
var ToDate = $('#dateTo').val();
var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
$.ajax
({
type: "POST",
url: '{{ route('invoice_details_export') }}',
data: dataString,
cache: false,
xhrFields:{
responseType: 'blob'
},
success: function(data)
{
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = `Invoice_details_report.xlsx`;
link.click();
},
fail: function(data) {
alert('Not downloaded');
//console.log('fail', data);
}
});
}
It's late but help for others
You can do this way
In Ajax
$(document).on('click', '#downloadExcel', function () {
$("#downloadExcel").hide();
$("#ExcelDownloadLoader").show();
$.ajax({
url: '{{ route("admin.export_pending_submitted_tasks") }}',
method: "GET",
cache: false,
data: {
search_partner,
search_state,
search_city,
_token,
},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
},
error: function (ajaxContext) {
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
alert('Export error: '+ajaxContext.responseText);
}
});
});
In Controller
// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
$input = $request->input();
$pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';
$pendingTaskList = $pending_submitted_tasks->where('status', 'pending')->get();
if($pendingTaskList->count() > 0):
$myFile = Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
$response = array(
'name' => "Pending-Task-List.xlsx",
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
);
return response()->json($response);
else:
return back()->with('message', 'No Pending tasks available to download!!');
endif;
}
If you are using jquery:
// In controller:
return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);
// Ajax:
$.ajax({
type: 'GET',
url: '{{ route("some.route") }}',
data: {
"_token": "{{ csrf_token() }}"
},
xhrFields:{
responseType: 'blob'
},
beforeSend: function() {
//
},
success: function(data) {
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(data);
window.open(objectUrl);
},
error: function(data) {
//
}
});
I have the following select2 to load remote data with pagination:
$(".js-location-lookup").select2({
ajax: {
url: '/locations',
dataType: "json",
delay: 150,
data: function (params) {
return {
term: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data.data, function (item) {
return {
id: item.id,
text: item.name
};
}),
pagination: {
more: (params.page * data.per_page) < data.total
}
};
},
cache: true
},
minimumInputLength: 2,
placeholder: "-- Select --",
allowClear: true
});
Controller action:
public function getLocations(Request $request)
{
$term = $request->input('term');
$data = Location::where('name', 'LIKE', '%'.$term.'%')->paginate(5);
$data->appends(['term' => $term ]);
return response()->json($data);
}
the json:
{
"total":22,
"per_page":5,
"current_page":1,
"last_page":5,
"next_page_url":"/locations?term=en&page=2",
"prev_page_url":null,
"from":1,
"to":5,
"data":[
{"id":1,"name":"England"},
{"id":13,"name":"London (Central)"},
{"id":18,"name":"North East England"},
{"id":23,"name":"North West England"},
{"id":30,"name":"South East England"}
]
}
Only the first page loads and displays the text load more results but it doesn't scroll or do anything to show the next set of results?
If the number of items per page when displayed is less than the height of the dropdown box when it is open then the scroll bars on the select widget do not appear and the above behavior is observed i.e. you are unable to scroll to load the next set of data.
The fix was to increase the pagination to 10 per page so that they are more than the height of the dropdown box.
Not sure if you would class this as a bug.
public function getdataforselect2(Request $request){
if ($request->ajax()) {
$term = trim($request->term);
$posts = DB::table('channels')->select('id','name as text')
->where('name', 'LIKE', '%' . $term. '%')
->orderBy('name', 'asc')->simplePaginate(10);
$morePages=true;
// $pagination_obj= json_encode($posts);
if (empty($posts->nextPageUrl())){
$morePages=false;
}
$results = array(
"results" => $posts->items(),
"pagination" => array(
"more" => $morePages
)
);
return \Response::json($results);
}
}
<script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<!--<![endif]-->
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script> <script >
(function() {
$("#channel_id").select2({
placeholder: 'Channel...',
// width: '350px',
allowClear: true,
ajax: {
url: '/dataforselect2',
dataType: 'json',
delay: 250,
data: function(params) {
return {
term: params.term || '',
page: params.page || 1
}
},
cache: true
}
});
})();
</script>
Code here!
Use the following codes with the latest select2 version library.
Controller Codes:
public function getLocations(Request $request)
{
if ($request->ajax()) {
$page = $request->page;
$resultCount = 5;
$offset = ($page - 1) * $resultCount;
$locations = Location::where('name', 'LIKE', '%' . $request->term. '%')
->orderBy('name')
->skip($offset)
->take($resultCount)
->selectRaw('id, name as text')
->get();
$count = Count(Location::where('name', 'LIKE', '%' . $request->term. '%')
->orderBy('name')
->selectRaw('id, name as text')
->get());
$endCount = $offset + $resultCount;
$morePages = $count > $endCount;
$results = array(
"results" => $locations,
"pagination" => array(
"more" => $morePages
)
);
return response()->json($results);
}
return response()->json('oops');
}
View/JS Codes:
$(document).ready(function() {
$('.js-location-lookup').select2({
delay : 200,
ajax: {
url: '/locations',
dataType: 'json',
cache: true,
data: function(params) {
return {
term: params.term || '',
page: params.page || 1
}
},
}
});
});