Download maatwebsite excel using ajax in laravel - ajax

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

Related

Column can not be null in ajax laravel update function

Hi guys i am sending my updated values from ajax to my update function.i am getting error as "Column cannot be null"
Here is my input which i am sending json data:
<input type="text" id="jsonData" name="jsonData">
And here is my ajax form:
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#jsonData').val();
var sort_order = $('#sort_order').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log('json',jasondata);
//return false;
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
window.location.href ="/eqtype-editor";
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
and here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
From ajax when i console i am getting my json data..i am getting error as qtype_json cannot be null.
Can anyone help me where i am missing it.
Thanks in advance.
You use a wrong key for your data.
Change the line in your controller:
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
to
$qtype_editor->qtype_json = json_decode($request->input('qtype_json'));
and it will work.

Ajax laravel dropdown not returning the id of selected value

I am passing the hotel id as a parameter to my function to get all the rooms in that hotel. But it is returning an error. I want to return in a JSON format the id of the hotel.
this is my javascript function
function showRooms($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
var token = $('meta[name="_token"]').attr('content');
$.ajax({
url: '/rooms'+id,
type: "Get",
dataType: 'JSON',
data: "{id:" + JSON.stringify(id) + ", _token:" + token + "}",
success:function(data)
{
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
this is my controller
public function rooms(id $id){
$response = array();
$response =$id;
return response()->json($response);
}
this is my route
Route::get('/rooms', 'HomeController#rooms')->name('/rooms');
your URL url: '/rooms'+id, and Route::get('/rooms', 'HomeController#rooms')->name('/rooms'); not valid, please see my code i am edited your code
//Change your js function
function showRooms(hotel_plan_id) {
var id = hotel_plan_id;
if (id !== "") {
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('rooms', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
}
}
//Change your function
public function rooms($id){
return response()->json(['id'=>$id]);
}
//Change your route
Route::get('rooms/{id}', 'HomeController#rooms')->name('rooms');
***Use Route like this in routes.php file:**
Route::get('/rooms', 'HomeController#rooms');
public function rooms(Request $request){
$id = $request->get('id');
$response['id'] = $id;
**Or whatever you want to do and append in response varaible and return**
return response($response)->header('Content-Type', 'application/json');
}

error in image while uploading through ajax

I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}

laravel 4 upvote via ajax post

I can't seem to get my voting system to work in ajax. I'm trying to establish the 'upvote' and have my onclick function call my route and insert a vote accordingly, except nothing happens. I can't see why or where I'm going wrong.
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController#upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
You are using post in your jquery, but you are waiting for a GET route.
Use...
Route::post('knowledgebase/upvote/{id}', 'PostController#upvote');
Additionally, the way you are handling your route may not work correctly with the id. It would be expecting the id in the URL so what you can do is append your id to the url when setting up the ajax.
url: "http://domain.com/knowledgebase/upvote/"+id,
Or not use it at all, take the {id} portion out of your route, and grab it using Input::get('id');

Laravel 4 render view AJAX html is empty

public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.

Resources