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;
}
Related
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!
I have seen many topics like mine but I can't resolve my problem who seems so simple.
I have this function in JS :
function displayFullDesignation(id, select) {
var fullDesignation = $('option:selected', select).data('idacc');
var myId = parseInt(fullDesignation);
$.ajax({
url: '<?php echo $this->url(array('controller' => 'catalog', 'action' => 'fullname'));?>',
type: 'POST',
datatype: 'json',
data: {'id': myId},
success: function(data) {
if(data.success){
console.log(data.success);
}
}
});
return fullDesignation;
}
And in my controller :
/**
* AJAX Action
*/
public function fullnameAction($params) {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('fullname', 'json')->initContext();
$response = array();
$params = $this->getAllParams();
$listModels = Application_Model_Catalog_Accessory_List::getDesignationComplet($params['id']);
$response['success'] = true;
$response['aaData'] = $listModels;
$this->getHelper('json')->sendJson($response);
}
I don't know why I can't get anything from this ajax call. If I try to do a var_dump inside my function, it does nothing at all so I think that my call isn't good, but I have other calls who work like this.
What am I doing wrong please ?
And if I do a console.log of 'data', it gives me HTML. data.success gives me undefined.
Thanks !!
I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});
This is my Ajax call :
$("#cover-input").change(function(){
var file_data = $("#cover-input").prop("files")[0];
var form_data = new FormData();
form_data.append("cover_file", file_data);
//kaherdin
$.ajax({
url: 'update-cover',
type: 'POST',
dataType: 'script',
data: form_data,
contentType: false,
processData: false,
async: false,
success: function(resp){
console.log(resp);
},
error: function(err){
console.log('Likes error', err);
}
});
readURL_cover(this);
});
I've a function that basicly trim and upload a file on change.
public function updateCover(Request $request) {
$user = Sentinel::check();
$destinationPath = public_path('uploads/users');
if ($fileCover = $request->file('cover_file')) {
$input_cover = time().'.'.$fileCover->getClientOriginalExtension();
$img = Image::make($fileCover->getRealPath());
$img->fit(1920, 555, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input_cover);
// $user->cover = $input_cover;
$response = $input_cover;
return $response;
}
But this get me an error. I just want to get "input_cover" back to my ajax call so I can show the updated picture.
If I change : $response = $input_cover to $response = [$input_cover]; it kinkds of work but the input is like : ["my_pic.jpg"] so it's not nice.
You should return a JsonResponse like so:
return response()->json(['input_cover' => $input_cover]);
Check this for responses in json and how they work https://laravel.com/docs/5.4/responses#json-responses
CartController Method
public function update(Request $request, $id)
{
$product = Product::find($id);
$data['cart_item_id'] = $product->$id;
$data['cart_item_name'] = $product->name;
$data['cart_item_price'] = $product->price;
\Gloudemans\Shoppingcart\Facades\Cart::add($data['cart_item_id'], $data['cart_item_name'], 1, $data['cart_item_price']);
return Response::json(['success' => true, 'data' => $data]);
}
script:
<script type="text/javascript">
$('.item_add').click(function (event) {
event.preventDefault();
var data = $('.item_add').serializeArray();
$.ajax({
url: $(this).attr('href'),
data: data,
type: 'GET',
dataType: 'JSON',
success: function (html) {
alert('Hello')
}
});
return false;
});
</script>
view:
<a href="{{route('cart.update',$productItem->id)}}" class="item_add">
When Im watching network-request-response I get nothing, why don't I get data which i return from controller?
I checked your code and it works.
I can suggest you have forgotten to run "gulp" for your javascripts after you added ajax method in it (this is the only reason why you see nothing in "network-request-response"). Because, if ajax works then there would be a response (with or without error).