My codeigniter uploads images but not Json - codeigniter

I can successfully upload images to my codeigniter controller:
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->database();
}
function do_upload($folder)
{
$config['upload_path'] = './userdata/'. $folder . '/';
$config['allowed_types'] = 'gif|jpg|png|txt';
$config['max_size'] = '1000';
$config['max_width'] = '5024';
$config['max_height'] = '5768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
echo $this->upload->display_errors();
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}
}
The images are uploaded from my JS like so:
var formData = new FormData();
formData.append('userfile', this.image);
$.ajax({
url: 'upload/do_upload/atlas',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
}
});
Where this.image is the image file. Now this works fine so I know my controller and code works.
But when I try the same with a JSON string, the file is not uploaded:
this.json = JSON.stringify(parsedJSON, null, 4);
var formData = new FormData();
formData.append('userfile', this.json);
$.ajax({
url: 'upload/do_upload/json',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
}
});
Does anyone know why this works with images but not a Json string?

You can use standart process for sending json data to server
var json = JSON.stringify(parsedJSON, null, 4);
$.ajax({
url: 'upload/do_upload/json',
data: json,
type: 'POST',
success: function(data){
}
});

Related

laravel - ajax formdata wont show in controller

I have tried many different combination for AJAX Setup in order to send the formData to controller. Somehow I cannot get the form input inside my controller despite trying to return it will all type of ways. May I know what did I miss that causing me not be able to get the input in controller?
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
cache: false,
dataType: false,
contentType: false,
processData: false,
data:formData,
success: function (response) {
console.log(response);
return false;
},
});
});
public function update(Request $request){
$UserId = Auth::user()->id;
$Company = Company::where('id', Auth::user()->company_id)->first();
return $request->all();
}
use
<meta name="csrf-token" content="{{ csrf_token() }}">
in head
and jQuery code
$('#form_submit').submit(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var base = window.location.origin;
let formData = new FormData(this);
let my_url = base + "/article-store";
$.ajax({
type: 'post',
url: my_url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
},
error: function (data) {
}
});
});
After quite a bit of digging, since what I am doing is using the PATCH request, it's still not working as of now with FormData. To solve it, we need to spoof the method by appending the PATCH method to formData and our AJAX settings to be changed to POST. Then you'll receive all the request inside your controller.
Reference:
https://laracasts.com/discuss/channels/laravel/ajax-formdata-and-put-fails
https://laracasts.com/discuss/channels/javascript/axiosajax-http-patch-requests-with-file-not-working
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
formData.append('_method', 'PATCH');
console.log(Array.from(formData));
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: url,
data:formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
return false;
},
});
});

Why my controller not getting data from ajax

I'm new to this, I'm trying to get the data from an ajax query
This Is My Ajax
$('#insertfile').on('click',function() {
console.log('a');
var file = document.getElementById('files').files[0];
var name = document.getElementById('names').value;
if( $('#room-status-no').prop('checked') ) {
console.log("status: 1");
var status = 1;
} else {
var status = 0;
console.log("status: 0");
}
var id = document.getElementById('id').value;
let form = new FormData();
console.log(file);
form.append('file', file);
form.append('name', name);
form.append('status', status);
form.append('id', id);
form.append('_method', 'PATCH');
form.append('action', 'update_file');
console.log(id, name, status);
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('this is my route.update', 'update_file') }}",
type: "PATCH",
cache: false,
processData: false,
contentType : false,
dataType: 'json',
data: form,
beforeSend: function() {
$('body').append('<div id="spinnerLoading"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div>');
},
This is my Controller
public function update(Request $request) {
$action = $request->action;
dd($request->all());
if($action == 'update_text'){
return $this->updatetextControl($request);
} else if($action == 'update_file') {
return $this->updateFileControl($request);
}
I'm trying to pass the form data to my laravel controller using dd($request->all());
I was unable to get any data in my controller, I'm not sure if my URL route is the problem or I cant have multiple update functions others thing in one controller, does anyone know a solution? it will be much appreciated, thanks

Q: how to make form validation codeigniter with ajax?

Hello guys i try to make form validation codeigniter with ajax server side but it still not working, i want to make error message 'required' display under form input. what is it wrong in my code.
this is my controller
function ajax_submit_kategori() {
$this->load->library('form_validation');
$data['nama'] = $this->input->post('kategori');
$data['id_legislator'] = $this->input->post('legislator');
$this->db->insert('galangsuara_has_categories',$data);
$return['status'] = '0';
echo json_encode($return);
}
this is my ajax
<script type="text/javascript">
$('#input').submit(function(event){
event.preventDefault();
Pace.track(function(){
var cate = $('#tim').val();
var dapi = $('#dapil').val();
var legi = $('#legislatif').val();
$.ajax({
url: "<?= site_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
$("#modal_tambah").modal('hide');
document.getElementById("input").reset();
var table = $('#table').DataTable();
table.ajax.reload();
window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});
});
return false;
});
anyone can help me? :(
Try This
Controller code:
function ajax_submit_kategori() {
$status = 1;
$error = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('kategori', 'Kategori', 'required');
$this->form_validation->set_rules('dapil', 'Dapil', 'required');
$this->form_validation->set_rules('id_legislator', 'Id_legislator', 'required');
if ($this->form_validation->run() == FALSE) {
$status = 0;
$error = validation_errors();
} else {
$data['kategori'] = $this->input->post('kategori');
$data['dapil'] = $this->input->post('dapil');
$data['id_legislator'] = $this->input->post('id_legislator');
$this->db->insert('galangsuara_has_categories', $data);
}
$return['status'] = $status;
$return['$error'] = jsone_encode($error);
echo json_encode($return);
exit();
}
ajax code :
$.ajax({
url: "<?= base_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
//here, first you need to check your data is perfect for error then do according to your wish
//$("#modal_tambah").modal('hide');
//document.getElementById("input").reset();
//var table = $('#table').DataTable();
//table.ajax.reload();
//window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});

Download maatwebsite excel using ajax in laravel

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

Using ajax fileupload and codeignitert to save blob on server

So in my project the user can record himself and then I get a blob file from a recorderplugin I'm using. I'm trying to upload that blob to the server via a fileupload ajax call in codeigniter but I cannot find out how to get it working.
This is my javascript code: (
recorder.exportWAV(function(blob) {
console.log(blob);
$.ajaxFileUpload({
url : "../ajax/saverecording/",
secureuri :false,
fileElementId  :"geenidee",
dataType : blob.type,
data: blob.data,
success: function(data, status) {
if(data.status != 'error')
alert("hoera!");
alert(data.msg);
}
});
});
This is my saverecording function in the ajax.php controller
public function saverecording()
{
$status = "";
$msg = "";
$file_element_name = 'komaan';
if ($status != "error")
{
$config['upload_path'] = '../../upload/audio/recordings/';
$config['allowed_types'] = 'wav';
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
echo 'alert("this is not working!");';
}
else
{
$data = $this->upload->data();
}
#unlink($_FILES[$file_element_name]);
}
}
$this->upload->do_upload($file_element_name) is returning false but why I don't know. Can someone help?
Thanks!
You cannot modify the file input but you can upload it with ajax:
recorder.exportWAV(function(blob) {
$.ajax( "something.php", {
data: blob,
processData: false,
contentType: false,
method: "POST",
success: function() {
}
});
});

Resources