Export CSV using Laravel via Ajax - php

I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.
Here is my code :
route.php
Route::get('/title/show', 'TitleController#show');
Route::post('/title/show', 'TitleController#exportFromDB');
show.blade.php
<script>
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.ajax({
url: "",
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
}
})
})
})
TitleController.php:
$dataExport['Oversea'] = $dataOversea;
$this->titleRepository->export('csv', $properties, $dataExport);
TitleRepository.php
public function export($type, $properties, $data)
{
if (in_array($type, self::EXPORT_TYPE)) {
try {
return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {
$excel->setTitle($properties['_title']);
$excel->setCreator($properties['_creator'])
->setCompany($properties['_company']);
$excel->setDescription($properties['_description']);
$excel->sheet('Sheet', function ($sheet) use ($data) {
foreach ($data as $item) {
$sheet->fromArray($item);
}
});
})->export($type);
} catch (Exception $error) {
throw $error;
}
}
}
How can I fix them ? Thank !

Try this -
Don't write the code for export in your controller method, instead just save the excel file in your public folder.
Your controller method should return the filename.
On your ajax success do this -
location.href = path/to/file/property_title.xls
So replace your this line
->export($type);
with
->store($type, 'public/reports/', true);

I see your ajax url null value
Change it to
url : "{{ action('TitleController#exportFromDB') }}"
After that, response is data you return in controller
success: function (response) {}

I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:
public downloadItemsExcel() {
$items = Item::all();
Excel::create('items', function($excel) use($items) {
$excel->sheet('ExportFile', function($sheet) use($items) {
$sheet->fromArray($items);
});
})->export('xls');
}
This works for csv/excel files alike. There is no reload of a page in the browser.

First you have to change POST method to GET.
For ajax you can do it like this:
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.get('/title/show, function(data){
window.location = '/title/show=' + data;
});
})
})

Related

I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and Ajax but getting an 500 internal server

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}

ajax json working on local but not on remote server codeigniter

Visit here and the search bar in front is the autocomplete
it is working fine when I use on localhost and appends results in the li under but when I have uploaded on live server it shows 404.
This is the link to custom.js on which browser shows 404();
Main: Custom.js:
$(document).ready(function () {
$("#CompanyName").keyup(function () {
$.ajax({
type: "POST",
url: "http://www.sonnify.de/reviewotter/autocomplete/GetCompanyName",
data: {
keyword: $("#CompanyName").val()
},
dataType: "json",
success: function (data) {
if (data.length > 0) {
$('#Dropdowncompany').empty();
$('#CompanyName').attr("data-toggle", "dropdown");
$('#Dropdowncompany').dropdown('toggle');
alert("i am here");
}
else if (data.length == 0) {
$('#CompanyName').attr("data-toggle", "");
}
$.each(data, function (key,value) {
if (data.length >= 0)
$('#Dropdowncompany').append('<li role="displayCompanies"
id="displayCompanies" ><a role="menuitem
dropdowncompanyli" class="dropdownlivalue">' +
value['CompanyName'] + '</a></li>');
});
}
});
});
$('ul.txtcompany').on('click', 'li a', function () {
$('#CompanyName').val($(this).text());
var CompanyName = $(this).text();
alert(CompanyName);
window.location.href = "http://localhost/reviewotter/company2?
company="+CompanyName+"";
//window.location.href = "http://localhost/reviewotter/company2?
lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
});});
Model: datacomplete.php:
<?php
class Datacomplete extends CI_Model{
public function GetRow($keyword) {
$this->db->order_by('Id', 'DESC');
$this->db->like("CountryName", $keyword);
return $this->db->get('company')->result_array();
}}
Controller: autocomplete.php
<?php
class Autocomplete extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('datacomplete');
}
public function index(){
//$this->load->view('view_demo');
$this->load->view('home');
}
public function GetCompanyName(){
$keyword=$this->input->post('keyword');
$data=$this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>
Let me guess, localhost is on a Windows machine but the live server is Linux? Then it is probably a case sensitivity problem. Linux is a case-sensitive OS.
The model file datacomplete.php should be Datacomplete.php (Notice the uppercase first character?) and the controller autocomplete.php should be Autocomplete.php.
You will be able to get this resolved by adding a custom route. Please add below line to application/config/routes.php file.
$route['autocomplete/get-company-name'] = 'Autocomplete/GetCompanyName';
You will have to adjust your JQuery AJAX function according to the new URL. Also can remove the index.php from the URL. Please refer below link.
https://www.codeigniter.com/userguide3/general/urls.html#removing-the-index-php-file

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

How to send a file via Axios to Laravel

I need to post a File from client to server via Axios.
Here is my Vuejs code :
methods: {
'successUpload': function (file) {
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios.post('/Upload/File',file, config).then(function (response) {
console.log(response.data);
});
}
}
And here is my Laravel code for handling sent file :
public function uploadFile(Request $request)
{
if($request->hasFile('file'))
return "It's a File";
return "No! It's not a File";
}
But it always returns No It's not a File.
Any helps would be great appreciated.
You have to create a FormData object and append the image file.
methods: {
'successUpload': function (file) {
let data = new FormData();
data.append('file', document.getElementById('file').files[0]);
axios.post('/Upload/File',data).then(function (response) {
console.log(response.data);
});
}
}
An example is here.
Let me know if that works.

ajax post and redirect to new page not work

I use resource make crud, and in the create page, I have to add a preview page
I tried to use ajax post data to admin/article/previewform then in route action controller method previewform catch data and store in variable with redirect to new page preview show it ...
I have problem
1. Why it doesn't redirect to new page ?
2. Why in js console.log get Faild to load resource … statu?s of 500
3. I also try return Redirect::to('admin/article/previewshow'); in previewform then still not redirect to.
But get js console.log with template show.blade.phpthat is in resource show method call.. ??
How to solve it?
js
$.ajax({
url: 'previewform',
type: 'POST',
data: {data: data},
})
.done(function(response) {
console.log(response);
});
route
//.. prefix=>admin
Route::resource('article','AdminArticleController');
Route::post('admin/article/previewform', 'AdminArticlePreviewController#previewform');
Route::get('admin/article/preview', 'AdminArticlePreviewController#preview');
AdminArticlePreviewController
class AdminArticlePreviewController extends AdminController
{
public function preview()
{
$input = Input::get('data');
return Redirect::route('admin/article/previewshow');
}
public function previewshow()
{
// return View::make('admin.article.preview')->with('data', $data)
}
}
It is not possible to make redirection in this way. For ajax requests you need to catch "redirection command" from the server side script (PHP) and execute it in the JS.
Instead:
return Redirect::route('admin/article/previewshow');
you can use:
return Response::make('/redirect/url', 301)
then JS code:
.done(function(response) {
console.log(response);
});
can be replaced by something like:
.done(function(data, statusText, xhr) {
if(xhr.status == 301) {
window.location = data;
}
});

Categories