I'm trying to fetch file via ajax from the laravel storage (I don't want to use the public folder as the docs should be only available for the admins). So the Ajax function calls a Route (post) , which calls the controller function to respond, but getting 500 internal server error in the console all the time.
If I dd() the request, or some string right in the begining of the controller function I get that back as output. so the request actually happens with the proper data. CSRF tokens are included.
The route:
Route::post('/tes/admin/filter/docview/', 'AdminTravelExpenseController#showdoc')-
>name('admin.tes.displayDoc');
The controller:
public function __construct()
{
$this->middleware('auth');
//adminvalidator here
}
public function showdoc(Request $request){
$item = \App\TravelExpense::find($request['id']);
if($request['src'] == 1){
$url = $item->doc_url1 ;
}
else{
$url = $item->doc_url2 ;
}
if (!Storage::disk('local')->exists($filePath)){
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return \Response::json($response);
}
And the ajax:
$('.docview').on('click',function(){
var id = $(this).data('id');
var src = $(this).data('src');
var form_data = new FormData();
form_data.append('id', id);
form_data.append('src', src);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/tes/admin/filter/docview/',
type: "POST",
processData: false,
contentType: false,
data: form_data,
success: function(data){
console.log(data);
$('.docDisplay').html(data);
}
});
});
Not sure what I'm missing here.
Thanks for the help in advance!
Related
I'm trying to send via AJAX data, I'm doing a post and then receiving it on the laravel controller.
I'm getting an error that the data is null.
I tried multiples ways to fix it but I'm not able to figure out how to do it.
Ajax:
$(document).ready(function () {
$('table tbody').sortable({
update: function (event, ui) {
$(this).children().each(function (index) {
if ($(this).attr('data-position') != (index + 1)) {
$(this).attr('data-position', (index + 1)).addClass('updated');
}
});
saveNewPositions();
}
});
});
function saveNewPositions() {
var positions = [];
$('.updated').each(function () {
positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(positions);
$.ajax({
url: 'cursos',
method: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(positions),
contentType: "application/json; charset=utf-8",
traditional: true,
})
}
Laravel Controller:
public static function updateOrder(Request $request)
{
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
Doing a dd of the request, I receive this:
I fixed it using $request->toArray() instead of $request->positions directly
From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
I have a problem with the following code in Laravel. I need to send some variables to my controller, do something with them and return three variables back. I made have made the ajax call, the route and the controller but the ajax call fail. As an error code I receive this.
View
function gg() {
var slider_value = document.getElementById('paradnyi').value;
var checkbox_value = document.getElementById('check_box').value;
var dto = {slider_value : slider_value, checkbox_value : checkbox_value};
$.ajax({
url : "/calc_change",
contentType : 'application/json',
data : JSON.stringify(dto),
type : 'POST',
success: function(data) {
document.getElementById('visits').innerHTML = data[0];
document.getElementById('slaves').innerHTML = data[1];
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
}
Routes
Route::post('/calc_change',['uses'=>'PagesController#calc_change','as'=>'calc_change']);
Controller
public function calc_change(Request $request){
$data = array();
$data[]=1;
$data[]=2;
//dd($data);
return response()->json($data);
}
You have to add this code before ajax call in jquery section
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I am working on a Laravel 5.3 solution. I try to call a POST route via AJAX from one of my views to update a set of categories but I get a 404 error everytime I call the route.
Interesting fact: During development I was able to call the route with the JS-code shown below successfully - but since I did some updates to the controller code itself it throws a 404 but no exception.
Here is my controller action:
public function updateTree( Request $request )
{
$data = $request->json()->all();
$result = BlogCategory::rebuildTree($data, false);
if($result > 0) {
return Response::HTTP_OK;
}
return Response::HTTP_NOT_MODIFIED;
}
And here the JS AJAX call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var updateTree = function (e) {
var list = e.length ? e : $(e.target), output = list.data('output');
console.log(JSON.stringify(list.nestable('serialize')));
$.ajax({
url: '{{ action('BlogCategoryController#updateTree') }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
};
$(document).ready(function() {
$('#nestable2').nestable({
group: 1
}).on('change', updateTree);
});
The controller route is bound like that in web.php
Route::post( '/service/blog/categories/updatetree', 'BlogCategoryController#updateTree' );
As you might see, I am using the Laravel NestedSet module from LazyChaser here (https://github.com/lazychaser/laravel-nestedset).
Any input is much appreciated.
Cheers,
Jules
you having opening and closing quotes problem in your ajax url, use like this
$.ajax({
url: '{{ action("BlogCategoryController#updateTree") }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');