I have a shopping cart which is stored in session and I want to refresh the session without reloading the page
I have tried this:
View:
Add to cart
<script>
$(document).ready(function() {
$('#product').click(function(event) {
event.preventDefault();
let url = "{{ route('add-to-cart') }}";
let id = $(this).data('id');
$.ajax({
url: url,
type: 'POST',
data: {product_id: id, _token: "{{ Session::token() }}"}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
});
});
Route:
Route::post('/add-to-cart', 'ProductsController#addToCart')->name('add-to-cart');
ProductsController:
public function addToCart(Request $request)
{
if ($request::ajax()) {
$id = $request->product_id;
$product = Product::find($id);
if (Session::has('products')) {
$products = Session::get('products');
$products[] = $product;
Session::put('products', $products);
}
else {
$products = array($product);
Session::put('products', $products);
}
return response()->json();
}
}
And when I click add to cart it gives 500 (Internal Server Error) in the console
You're accessing the ajax() method statically (using ::), when you should be using -> instead:
if ($request->ajax()) {
Using the Laravel log file
As mentioned in the comments, Laravel is probably telling you this in storage/logs/laravel.log, complete with a long call-stack trace (the lines that you mentioned, beginning with "#38" and "#39"). Just scroll up to before "#1" and you'll find your culprit.
Laravel doesn't allow without passing X-CSRF-TOKEN,
following is my working example hope it helps you.
Route :
Route::post('block-user','UserController#BlockUser');
Now you need to add ajax setup before your ajax call so in
blade.php :
Add this in header
<meta name="csrf-token" content="{{ csrf_token() }}" />
My script like :
<script>
//Ajax setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Ajax call
$(".blockuser").bootstrapSwitch();
$('.blockuser').on('switchChange.bootstrapSwitch', function () {
var userid = $('#userid').val();
$.ajax({
url:'/block-user',
data:{user_id : userid},
type:'post',
success: function(data){
alert(data);
}
});
});
</script>
Controller :
public function BlockUser(Request $request)
{
$userid = $request->get('user_id');
//perform operation
}
Related
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 8 months ago.
I'm trying to make a sortable table in my laravel app where the order also needs to be updated in the database, I'm trying to do it with jquery, ajax.
I tried to figure it out with this pieces of code:
JQuery/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 () {
position.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'cursos',
method: 'POST',
dataType: 'text',
data: {
'updated': 1,
'positions': positions,
'_token': '{{ csrf_token() }}'
},
})
Then in my web.php I created a post route:
Route::post('/cursos', function (Request $request){
return SectionCourseController::updateOrder($request);})->name('post');
In my controller I created this function:
public static function updateOrder(Request $request)
{
var_dump($request->positions);
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
When I'm trying to update the order, I'm having an error on the console of 500 (Internal Server Error).
[2022-06-14 14:16:18] local.ERROR: foreach() argument must be of type array|object, null given {"userId":1,"exception":"[object] (ErrorException(code: 0): foreach() argument must be of type array|object, null given
Sorry if I'm doing something bad on Ajax, this is the first time I try to do something on it.
I've done something very similar to this, so as I see it right now you are firstly missing a csrf token, so in the view add this below the code where you declare the $('updated') each.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'POST',
dataType: 'json',
url: 'cursos', // No {{}} needed here
data: {
update: 1,
orders: orders,
_token: '{{ csrf_token() }}'
},
});
Next your controller is a mess. So rewrite it to fit at least some of laravels writing standards. Something like this
public 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);
}
Also add the following when declaring .sortable
axis: 'y',
containment: 'parent',
update: ...
Add a meta-tag to each page, or master layout
<meta name="csrf-token" content="{{ csrf_token() }}"> and add to your js page
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Dont forget to add data inside
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
There is 2 cases for 500 internal server error
you had not put the {csrf} token there when sending request through ajax.
Use new FormData() object while sending response through ajax and use these params with processData: false,contentType: false,type: 'POST'
Can someone tell me what's missing in my ajax request? I originally thought it was the _token but I still don't get a 200 response. Maybe it's a missing parameter in my function? Below is my code, built on Laravel.
View.blade.php
callback: function (result) {
if(result == true){
$('#common_loader').show();
$.ajax({
method:'POST',
data: {'offer_id': offer_id,'_token':'{{ Session::token() }}'},
cache: false,
url: "{{url('/chooseArtist')}}",
success: function (data) {
$('#common_loader').hide();
var rep = JSON.parse(data);
if (rep.status == 200) {
bootbox.alert(rep.response);
/// code continues.
Route
Route::post('/chooseArtist', [ProjectController::class, 'chooseArtist']);
Controller Function
public function chooseArtist() {
$data["status"] = 200;
echo json_encode($data);
die;
}
I don't think you can include the CSRF token that way on more recent versions of Laravel? Include it in the meta tag of your page :
<meta name="csrf-token" content="{{ csrf_token() }}" />
And then incorporate it into your script before your Ajax call :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Separately, on the frontend you're trying to bootbox alert "rep.response" but on the back end your response only contains the status, not anything else. Also, rather than echo it, you should return the result.
$data = array();
$data['status'] = 200;
$data['response'] = "Jimi Hendrix";
return (json_encode($response));
Laravel post request csrf token in data attribute.
Try this solution:
callback: function (result) {
if(result == true){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#common_loader').show();
$.ajax({
method:'POST',
data: {_token: CSRF_TOKEN,'offer_id': offer_id,'_token':'{{Session::token() }}'},
cache: false,
url: "{{url('/chooseArtist')}}",
success: function (data) {
$('#common_loader').hide();
var rep = JSON.parse(data);
if (rep.status == 200) {
bootbox.alert(rep.response);
/// code continues.
i'm creating function delete in laravel and here is my Controller
public function removePetitions($id)
{
$rm = Petitions::find($id);
$rm->delete();
return ['status' => true];
}
and here is my route
Route::post('/delete/petition/{id}','Admin\PetitionController#removePetitions')->name('admin.delete');
when i click button delete in view it show MethodNotAllowedHttpException. anyone solve that??? thank u
If i understand your problem You are looking for this kin of stuff
Your anchor tag here look like this:-
Del
And route looklike this :-
Route::post('/delete/petition','Admin\PetitionController#removePetitions');
And now ajax code :-
<meta name="csrf-token" content="{{ csrf_token() }}" /> // add in head tag
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click','.btn-del-petition',function(){
var id = $(this).attr('data-id');
$.ajax({
type: 'post',
url: 'delete/petition',
data: {id :id},
success:function(resp){
alert(resp);
//Delete that deleted row with jquery
},
error:function(){
alert('Error');
}
})
})
Now your function :-
public function removePetitions(Request $request)
{
if($request->ajax()){
$data = $request->all();
$rm = Petitions::find($data['id']);
$rm->delete();
return ['status' => true];
}
}
Hope it helps!
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 have created a like and dislike a button and store the info through ajax in Laravel 5.2. I am using wamp as my localhost.
At first, I saw sometimes the like and dislike was counted, and sometimes they weren't.
So, I tried to see it in the console through console.log(), and found 500(internal Server Error) in some of my clicks.
I also made sure the csrf token is provided properly.
I don't know how to deal with an error which sometimes come and sometimes doesn't.
this is my likeajax.js :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var postId=0;
$('.option1').on('click', function (event) {
event.preventDefault();
$('event').attr('disabled', 'disabled');
postId = event.target.parentNode.parentNode.parentNode.parentNode.dataset['postid'];
$.ajax({
method: 'GET',
url: urlLike,
data: {postId: postId, _token: token},
})
});
$('.optionx').on('click', function (event) {
event.preventDefault();
$('event').attr('disabled', 'disabled');
postId = event.target.parentNode.parentNode.parentNode.parentNode.dataset['postid'];
$.ajax({
method: 'GET',
url: urlDislike,
data: {postId: postId, _token: token},
})
});
this is my LikeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Depress;
use App\Http\Requests;
class LikeController extends Controller
{
public function postLike(Request $request)
{
$post_id = $request['postId'];
$post = Depress::find($post_id);
$post->like = $post->like+1;
$post->save();
return null;
}
public function postDislike(Request $request)
{
$post_id = $request['postId'];
$post = Depress::find($post_id);
$post->dislike = $post->dislike+1;
$post->save();
return null;
}
}
this is in my like layout.blade.php,
<script>
var token = "{{ csrf_token() }}";
var urlLike = '{{ route('like') }}';
var urlDislike = '{{ route('dislike') }}';
</script>
UPDATE:
though when I go to the page : http://localhost:8000/dislike ,
it shows
MethodNotAllowedHttpException in RouteCollection.php line 218:
Any help will be really appreciated.
The problem is that you $post_id is NULL.
Try $request->input('postId') instead of $request['postId'].
Also you should consider using POST instead of GET.