I have this ajax method in PostsController
public function ajax(Request $request)
{
//dd($request);
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments), 200);
}
which works great when you just getting data and sending it.
So i tried besides requesting data by ajax, to send some data alongside ajax request. How can i access that data inside controller?
Here is a method which resides inside certain blade:
function ajax(){
let var1 = "gg";
let var2 = "bruh";
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = '/posts';
$.ajax({
type: "POST",
url: url,
headers:
{
'X-CSRF-TOKEN': token
},
data: {
'var1': var1,
'var2': var2
},
success: function(data) {
console.log(data);
}
});
}
To simplify: How can i, dd() or dump(), given data(var1 & var2) by ajax function from blade in PostsController?
Here is route:
Route::post('/posts', "PostsController#ajax");
And here is some "gibberish" when i try to dd() it:
dd() is a laravel function and dump()for php. so you cannot use them from javaScript.
You cannot dd() or dump() from direct ajax request or JavaScript.
What you can do is, console log your data, or check from browser developer portion, network tab to see which data you are getting from the ajax response. You can find browser developer portion in,
for chrome:
Insepect > Network
for mozila:
Insepect Element > Network
If you are telling about get var1 and var2 on controller, you can just get them by $request->var1 and $request->var2.
Hasan05 was right. Just needed to know right direction. So to get data parameter of ajax request i modified ajax controller method:
public function ajax(Request $request)
{
$var1 = $request->input('var1');
$var2 = $request->input('var2');
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments, "var1"=> $var1, "var2"=> $var2), 200);
}
Related
I have ProjectController that fetches data from the database and passes it to a blade file. One of the data items is the project_id. I want to pass the project _id from the blade file to another controller BidController.
ProjectController.php
public function show($id)
{
$project = Project::find($id);
return view('project.show',['project'=>$project]);
}
show.blade.php
div class="card-header">PROJECT <p>{!! $project->id !!}</p></div>
BidController.php
public function store(Request $request)
{
$bid = new Bid;
$bid->project_id = $project_id;
dd($project_id);
}
The dd(); does not output the project_id. I need help in passing the project_id from the blade file to the BidController method.
You can't directly set a model's id like you're doing in the line $bid->id = $project_id;. Are you trying to set up a relationship? That should be more like $bid->project_id = $request->project_id;.
Blade templates can't really pass things back to controllers, once they're in the browser your app is sort-of finished running. You need to create an HTML link/request on the page (like a form post request) that'll request the next thing from your app when the user clicks it.
If you want to create a button that creates a new bid for an existing project, you could do something like set up a form with a hidden field of 'project_id' that posts back to '/bids' which goes to the route 'bids.store'. You'll find 'project_id' under $request->project-id'.
You can send an AJAX request from Javascript:
View
<script type="text/javascript">
var project_id= {!! json_encode($project->id) !!}
$.ajax({
type: 'POST',
url: url, //Your bidController route
data: {project_id: project_id},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
},
success: function()
{
console.log('successful')
}
});
</script>
This will sent the data to the controller asynchronously so the user experience doesn't get affected.
One extra point: In your Bid controller, as project_id is coming from the request, you'll have to use:
$bid->id = $request->project_id;
I hope it helps!
PS: I'm using JQuery for this, so you'll have to include it if you don't already have.
I think this will solve your problem :
ProjectController.php
public function show($id)
{
$project = Project::findOrFail($id);
return view('project.show',compact('project');
}
web.php
Route::post('/bids/store/{id}' , 'BidController#store')->name('bids.store');
show.blade.php
div class="card-header">PROJECT <p>{{$project->id}}</p></div>
<form action="{{route('bids.store', $project->id)}}" method="post">
BidController.php
public function store(Request $request, $id)
{
$bid = new Bid;
$bid->id = $id;
$bid->save();
dd($id);
}
I am using vue with laravel.but my save function not working. So I tried to dump and die the request object but I can't see the request object in the preview. it is blank.
protected function save()
{
$request = Request::all();
dd($request);
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['image'];
$suggestion->save();
return 'success';
}
the axios call is
axios.post('suggestion/save', this.post).then(response => {
this.$swal({
title: 'Success',
text: response.data.message,
type: 'success',
confirmButtonText: 'OK',
});
this.$router.push('/suggestion-list');
})
There are multiple Request classes in Laravel, One thing you can try is the following,
public function controllerFunction()
{
dd(request()->all());
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['description'];
$suggestion->save();
return 'success';
}
So irrespective of your class, the request() function will bring up the appropriate object.
If you get to dump the request then you can confirm that the request is hitting the appropriate controller function, otherwise, the request is going somewhere else. check the network tab in chrome for more details.
Also, make sure you have the appropriate Request class in the use statements.
The correct Request class usage is like following
use Illuminate\Http\Request;
Add request to your function
also add 'use Illuminate\Http\Request'
use Illuminate\Http\Request
public function myFunction(Request $request)
{
dd($request->all());
...
}
hey you can use print() or print_r() to check result
and make sure your this.post has data or not
I am using an ajax request to show some information, on my local development version it works perfectly, but on the production server (Ubuntu 16.04 LEMP) it fails in validation, because there is no data in the request.
Checks
The url is correctly showing (e.g. example.com/employeeInfo?employeeId=1)
Ajax itself is working: when I hard-code the controller's response everything is fine.
I cannot figure out why this happens in production, but not on the local version... Huge thanks for any clues!
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
var employeeId = $(this).data('id');
// Get data
$.ajax({
type: "GET",
url: "employeeInfo",
data: {employeeId:employeeId},
success: function(data){
var obj=$.parseJSON(data);
$('#team-info-title').html(obj.output_name);
$('#team-info-subtitle').html(obj.output_role);
$('#resume').html(obj.output_resume);
$('#linkedin').html(obj.output_linkedin);
$("#team-info-background").show();
$("#team-info").show();
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#getInfo');
Controller
public function getInfo(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'employeeId' => 'required|integer',
]);
$employee = Employee::find($request->employeeId);
$output_linkedin = '<i class="fab fa-linkedin"></i>';
$data = array("output_resume"=>$employee->resume,"output_linkedin"=>$output_linkedin, "output_name"=>$employee->name, "output_role"=>$employee->role);
echo json_encode($data);
}
}
If you want to pass a get data employeeId you have to pass a slug through your route either you should pass the data by POST method.
Route::get('/employeeInfo/{slug}', 'EmployeeController#getInfo');
And Get the slug on your function on controller .
public function getInfo($employeeId)
I got this error from Ajax call ! it's get action from checkbox then send data by Ajax to controller method,
jquery.min.js:4 POST http://localhost:8000/listhotelregisration 500 (Internal Server Error)
Here's the code html part:
<div style="display:block">
<div>My hotel Lists</div>
#foreach($myLists as $key => $val)
{{ $val['name'] }
{!! Form::checkbox($val['name'], $val['id'].','.$value['id']) !!} <br>
#endforeach
</div>
Ajax part:
$(function() {
$("input[type='checkbox']").change(function() {
var smi = $(this).val();
// alert(smi);
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {'checko':smi},
success: function(data){
//alert(data);
}
});
});
Route part:
Route::post('listhotelregisration', 'ListhotelController#create');
Controller part:
public function create(Request $request)
{
$listhotel = new listhotel;
$data = $request->all();
$dataPrim = explode(",", $data);
$listhotel->id_list= $dataPrim[0];
$listhotel->id_hotel= $dataPrim[1];
$listhotel->save();
$response = "ok";
return response ()->json ($response);
}
Ajax in Laravel 5
This is mainly due to The VerifyCSRFToken middleware that laravel provide us out-of-the-box. It responds an Internal Server Error (500) when token mismatch occur on our requests.
We need to send our AJAX request with token sent to our browser.
The CSRF token is mostly stored in the meta tag, you can put it any where though
$.ajaxSetup
Set default values for future Ajax requests
Solution
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
Hope this helps.
error 500 will mean this is a server error.
To know exactly what went wrong you need to check the response the server is returning.
In any case i would already adjust your following pieces:
Javascript:
$(function() {
$("input[type='checkbox']").change(function() {
var id_list = $(this).attr('id_list');
var id_hotel = $(this).attr('id_hotel');
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {
'id_list': id_list,
'id_hotel':id_hotel
}
}
});
});
Controller:
public function create(Request $request)
{
$data = $request->only(['id_list', 'id_hotel']);
$listhotel = listhotel::firstOrCreate($data)
return response ()->json ("OK");
}
I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.
Please see the code below :
web.php ( route )
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController#update');
});
My angularjs product service :
function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
My ProductController update function
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
This is what I see in Chrome inspectmen
Please share your experiences on this problem. Thanks.
what you need is Only normal POST request with new field named _method=put then your code will work normally:
You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
Try this method:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
Also, make sure you're using Route::put or Route::resource for your route.