Why does laravel $request->file return null? - laravel

I have a code that I am using in another app to upload files using Ajax which is working well.
Reusing this code in a new app with Jquery modal dialog is not working as expected. Below is my form:
{!! Form::open(['method' => 'POST', 'route' => ['auto-evaluation-documents.store'], 'files' => 'true', 'role' => 'form', 'id' => 'document_form']) !!}
<div class="modal-content" modal-transclude="" title="New Attachment">
<div class="form-group">
<input class="ng-scope" type="file" name="file" id="file">
</div>
</div>
{!! Form::close() !!}
Below is my modal dialog
var dialog;
dialog = $(".modal-content").dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
"Save": uploadFile,
Cancel: function() {
$('#file').val('');
$('.c-fileupload__body').hide();
dialog.dialog( "close" );
}
},
close: function() {
//form[ 0 ].reset();
//allFields.removeClass( "ui-state-error" );
$('#file').val('');
$('.c-fileupload__body').hide();
}
});
$("#new_attachment_button").button().on( "click", function() {
dialog.dialog( "open" );
});
Below is the upload file function
function uploadFile() {
var document_form = $('#document_form');
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
data: { 'document_type': 'file', 'evaluation_session_id':'2'},
url: document_form.attr('action'),
type: 'post',
dataType: 'json'
};
// attach handler to form's submit event
document_form.ajaxSubmit(options);
// return false to prevent normal browser submit and page navigation
return false;
}
// pre-submit callback
function showRequest(formData, jqForm, options) {
var file_msg = $('#file_msg');
file_msg.empty().hide();
var value = $('#file').fieldValue();
if (!value[0]) {
message = "<li>Please select a file to upload</li>";
file_msg.append(message).show();
return false;
} else {
formData.push({ 'name': 'file', 'value': value[0]});
return true;
}
}
In Laravel controller, I do:
public function store(Request $request)
{
$file = $request->file('file');
$return['success'] = true;
$return['file_name'] = $file;
return response()->json($return, 200, ['Content-Type' => 'text/html']);
}
However, when I check my console, the result I get for $request->file('file') is null
If I do $request->get('file'), I get C:\fakepath\banner-image.jpg
Why is $request->file('file') not working even though my form has enctype="multipart/form-data" ?
I have applied other solutions here with no success. Please help

You should try to dump $request->all(); to see if error is on front-end. If you have file named "file" error is in front-end/Angular.

Related

Stop previous ajax when new request is made 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.
controller
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>
jquery
$(".butonSubmit").click(function(){
if($(".carousel-item").hasClass('active') ){
let room_id = $(".carousel-item.active").find('.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 = response.events
);
console.log(result);
},
error: function(response) {
console.log(error);
},
});
}
});
It is because you do not update the calendar after new request. Previous values are still there on the calender

How to pass data from controller to view using AJAX

I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');

Form AJAX submit symfony doesn't work

I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.

Upload images via adjusted form and dropzone and codeigniter

Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.
Here is part of the form:
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
Here is the script:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
data: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function () {
this.on("addedfile", function (file) {
console.log(file);
});
}
});
Here is the controller
public function upload_image(){
if ($this->input->post()) {
$this->invoice_items_model->add_image($this->input->post());
}
}
Here is the modal
public function add_image($data){
$dat = array(
'rel_name' => $data['name'],
'rel_type' => 'cms_items',
'dateadded' => date('Y-m-d H:i:s')
);
$this->db->insert('tblfiles', $dat);
}
For the one that need an answer:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sucess",function(file, xhr, formData){
});
},
dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
dictRemoveFile : "<?=_l('remove_file')?>"
});

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

Resources