i'm trying to redirect to Controller with data and use that data in controller ( i'm using laravel)
/* html */
<a #click="Submit()" href="/buy" class="btn btn-block btn-lg btn-primary btn-checkout-pay">Buy</a>
/*js codes*/
Submit : function(){
axios.post('/buy',{
ProductId : this.id,
//ProductId : "1";//
ProductAmount : this.temporaryamount
//ProductAmount : "12000";//
})
.then(function (response) {
window.location = "/buy";
console.log(response);
})
.catch(function (error) {
console.log(error);
})
}
and the /buy is redirected to ShoppingController#create
/* web.php */
Route::get('/buy','ShoppingController#create');
Route::post('/buy','ShoppingController#create');
/* ShoppingController#create */
public function create(Request $request)
{
dd($request['ProductId']);
}
the problem is $request['ProductId']; is null
that means axois request is redirected without the data
P.S : i don't wan't to return the data i wanna just use the data in controller
Basically, you cannot used together those two create functions with different route method and at the same time you want to get the product id. Your post request will work on that situation but the get request will not. that's why dd($request['ProductId']) is null. You cannot use request as a parameter whenever you use a get request. $request as a parameter is for post request only.
for further explanation please read laravel docs source
so to solve your problem, you may remove this line
window.location = "/buy";
and show your post data in the controller by this
public function create(Request $request) {
dd($request->all())
}
if i understand correctly your problem is that you don't see the return of "dd".
It's normal your console.log is after the window! and no dd with axios! you have to return to see the answer!
Controller
public function create(Request $request)
{
return $request['ProductId'];
}
.vue
/*js codes*/
Submit : function(){
axios.post('/buy',{
ProductId : this.id,
//ProductId : "1";//
ProductAmount : this.temporaryamount
//ProductAmount : "12000";//
})
.then(function (response) {
console.log(response);
//Remove window.location, or if you dont remove you dont see console.log!
//window.location = "/buy";
})
.catch(function (error) {
console.log(error);
})
}
and on your route remove get.
/* web.php */
Route::post('/buy','ShoppingController#create');
Related
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);
}
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)
Okay let me explain first. I am sending a PUT request using ajax like this:
//ajax function
$(document).on("click", ".question_no", function(){
current_color = rgb2hex($(this).css('background-color'));
q_index = $(this).attr('id').slice(5);
id_team_packet = $("#id_team_packet").val();
// startTimer();
if (current_color != '#ffc966') {
$(this).css('background-color', "#ffc966");
var status = "orange";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{route('peserta.submit.ans.stat')}}',
method: 'put',
data: {q_index, id_team_packet},
success: function(data){
console.log(data)
}
})
}
})
NOTE I already have my CSRF token setup in my head, which I also include in my ajax setup as you can see below. It works great :). But once I protect that route with a Middleware, like this:
//middleware
public function handle($request, Closure $next)
{
if (Auth::user()) {
if (Auth::user()->role == 3) {
return $next($request);
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
//web.php
Route::middleware(['participant_only'])->group(function(){
Route::put('/peserta/submit-answer-status', 'PesertaController#submitAnsStat')->name('peserta.submit.ans.stat');
});
As you can see it only accepts logged in user with a role of '3'. If user tries to log in, it redirects to '/'. Now I also check if the request is using ajax, which I return a message with code 401. But unfortunately, when the middleware is applied and I ajax it, it returns this error:
message
exception Symfony\Component\HttpKernel\Exception\HttpException
file -\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php
line 203
But if once I remove the middleware it works. I don't know where the problem is. Oh on another note, If I exclude that particular route from verifycsrftoken it returns the right response both with the middleware and without.
My question is, where is the problem and how do I fix it? Thank you :)
I can not get the response from the controller with Ajax,what should I do?:
$("document").ready(function(){
$("#send").click(function(e){
e.preventDefault();
var question = $("input[name=question]").val();
$.ajax({
type: "POST",
url : "/Admin/question/store?token={{$t}}",
data : {'question':question},
success : function(data){
alert(data);
console.log(data);
}
});
});
});
and in the controller I just want to return a string for testing:
public function store(Request $request)
{
return "success";
}
For you to get the response in AJAX you must print the data, is it being print after the return? if not, try :
public function store(Request $request)
{
echo "success";
}
I solved it,
First problem was URL,I changed it to:
{!! route('store') !!}
And did not know to write my route in api!!!! instead of web
My ajax (in vue component) like this :
<template>
...
<a class="text-right" #click="detail">
Detail
</a>
...
</template>
<script>
export default{
...
methods:{
...
detail() {
this.$http.post(window.BaseUrl + '/shop/',{data: JSON.stringify(this.data)}).then(function (response) {
...
}).catch(function(error){
...
});
}
}
}
</script>
If user click a link, it will call detail method
In detail method used to send data via ajax
It will routes in laravel
The route like this :
Route::group(['prefix' => 'shop','as'=>'shop.'], function () {
Route::post('/', 'ShopController#index');
...
});
Then the route will call shop controller
The controller like this :
public function index(Request $request)
{
$param = $request->only('data');
$list = $this->shop_service->getList($param['cart_cache']);
return view('shop.index',compact('list'));
}
If the code executed, I want it will redirect to view blade laravel (return view('shop.index',compact('list'));)
How can I do it?
You can redirect to route in Ajax success which will call your desired funtion in controller like this:
Ajax
success:function(){
window.location.href(base_url+"/get/data");
});
For this to work, you should have following route and controller function
Route
Route::get('/get/data','YourController#getData');
Controller
public function getData(){
$list = // here write code to get desired data.
return view('shop.index',compact('list'));
}
Hope you understand.