Ajax delete with laravel 500 internal error - javascript

Hi there I am new on coding so forgive me if I am asking too much, I have this problem here this is my HTML code on blade laravel:
<button type="button" id="removecollaborator" value="{{$bank_id}}" class="btn btn-flat btn-default btn-sm delete-colaboration-button"
title="#lang('buttons.remove_option')">
<i class="material-icons">delete</i>
</button>
and here I have my ajax js:
<script type="text/javascript">
$(document).on("click", "button[id=removecollaborator]", function (data) {
var result = confirm("Are you sure you want to delete this collaborator?");
if (result) {
var bankid = $(this).val();
$.ajax({
method: "POST",
url: "{{ url('/banks/delete-bank-collaborators') }}",
data: {
_token: "{{ csrf_token() }}",
bank_id: bankid
},
success: function () {
$("button[id=removecollaborator][value=" + bankid + "]").parent().parent().parent().parent().fadeOut('slow');
},
error: function () {
console.log("error");
}
});
}
});
</script>
And here I have the controller:
public function deleteCollaborator(){
if(request()->ajax()) {
$bank_id = request()->input('bank_id');
$bank_invites = BankInvite::select('id')->where('bank_id', $bank_id)->get()->toArray();
BankInvitedUser::whereIn('bank_invites_id', $bank_invites)->delete();
return response()->json(Lang::get('general.bank_deleted'));
}
It does not work I do not know why it returns Failed to load resource: the server responded with a status of 500 (Internal Server Error). so it is the success but I think in the controller I have the problem can someone help me, please..?

try replacing
deleteCollaborator(){
with
deleteCollaborator(Request $request){
also is your route a Route::post()?

Related

Ajax value not being passed to the controller in Laravel

I'm trying to get a value from ajax request into my controller. My js function shows desired value in alert but when I try to pass this value as data into the controller, the controller received null.
I'm not sure if this is an error with my app logic or a different problem. I would appreciate any feedback.
The form
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
The Javascript
<script>
function hex2rgb(hex) {
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{hex:hex,_token:_token},
success: function(response){ // What to do if we succeed
if(data == "success")
alert(response);
},
error: function(response){
alert('Error'+response);
}
})
}));
}
return null;
}
</script>
The Controller
public function multiStepStore(Request $request)
{
$input = $request->get('hex');
dd($input);
}
I think that you probles is in your token, the correct form to get a token for send in ajax is:
Blade
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
Javascript
<script>
function hex2rgb() { //remove the data you are receiving
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{
_token: "{{ csrf_token() }}",
hex:hex,
},
success: function(response){ // What to do if we succeed
console.log(response);
},
error: function(response){
console.log('Error'+response);
}
})
}));
}
return null;
}
</script>
Controller
public function multiStepStore(Request $request)
{
dd($request->all());
}
Route
Route::post('/hex', 'Hexcontroller#multiStepStore')->name('niceActionController.multiStepStore');
to see the console.log you need to open your browser's inspector

MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)

i get this error when i click the button:
deletethisproduct is not defined at HTMLAnchorElement.onclick
i know it's not the best idea to use onclick but i'm using it because i want to get the product id from the model for this instance and pass it to the function
this is my link:
Delete
and this is the js function:
#section scripts{
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
var deletethisproduct = function (productid) {
$.ajax({
method: 'POST',
url: "/Cart/deletecart",
data: { "id": productid },
success: function (data) {
console.log(data);
// $("#mymodalBodyDiv").html(data);
},
error: function (msg) {
alert("something wrong" + msg);
}
});
}
</script>
}
so why it's not defined ? and is there any other idea that can i get the product-id for this instance and pass it to the function without the onclick() ?
Edit: i think jquery is not read or something like that i don't know why although i am using it in another view with the same links!
<button class="btn btn-dange mythis">this </button>
i tried simply to alert from this button but nothing has happen no alert and no errors appeared in the console it also didn't say that "$" is not defined !
$('.mythis').click(function () {
alert("hiiii")
}
Try this using jquery
It's more easy to use jquery for that type of thing (I think).
The link :
<a class="btn btn-danger delete" data-id="#item.product_id">Delete </a>
The function :
#section scripts{
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$('.delete').click(function(){
var productid = $(this).attr("data-id");
$.ajax({
method: 'POST',
url: "/Cart/deletecart",
data: { "id": productid },
success: function (data) {
console.log(data);
// $("#mymodalBodyDiv").html(data);
},
error: function (msg) {
alert("something wrong" + msg);
}
});
});
</script>
}
The "data-id" can be acces from jquery using .attr https://api.jquery.com/attr/

How do I post a variable to a Laravel 5 route from javascript?

I'm trying to send a simple notification id from javascript on click, to mark a notification is read.
I've spent hours on it, but I get an endless 500 server error
"The GET method is not supported for this route. Supported methods: POST."
Can anyone explain what I'm doing wrong???
The form in my blade looks like this
<form method="POST" action="{{ route('markAsRead', $notification->id) }}">
#csrf
<button type="submit" class="btn read-notification unread" id="notificationIcon-{{ $notification->id }}">
<i class="fas fa-envelope fa-2x"></i></br>
<small>Mark as read</small>
</button>
</form>
My javascript looks like this
$(".read-notification").on("click", function (e) {
if ($(this).hasClass('unread')) {
var mainDiv = $(this).closest(".notification");
var divId = $(mainDiv).attr("id");
var notificationId = divId.replace("notification-", "");
document.getElementById("notificationIcon-"+notificationId).innerHTML = "<i class=\"far fa-envelope-open fa-2x\"></i>";
$(this).removeClass('unread');
$(this).addClass('read');
$('.collapse').collapse('toggle');
$.ajax({
type: 'post',
url: 'markAsRead',
data: {'notificationId' : notificationId},
dataType: 'json',
success: function(response){
console.log("That worked!");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
// $(".read-notification").attr("action", "/" + notificationId + "/markAsRead");
}
})
My route like this
Route::post('markAsRead', 'NotificationController#markAsRead');
and my controller like this
public function markAsRead(Request $request) {
$user = \Auth::user();
$notification = $user->notifications()->where('id', $request->notificationId)->first();
if ($notification) {
$notification->markAsRead();
return back();
} else {
return back()->withErrors('Sorry, we had a problem');
}
}
but at the moment I can't get passed the route.
I've tried named routes and urls, but I always get the same error.
Any help much appreciated...

Simple Ajax in Laravel

In a Laravel app, I need to update some data in the database after a button is clicked, without reloading the page, thus requiring ajax. No data needs to parsed, only a function in one of the controllers should be invoked, so it's the simplest kind of ajax request.
Based on this example, I set up the following, but nothing happens. No error, no response from the check alert('success!'), nothing.
QUESTION: why does nothing happen? Could it be that the Javascript is not recognized at al?
Head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Routes - web.php
Route::post('/notificationsSeen','NotificationController#seen');
Controller - NotificationController.php
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => 'seen'));
return;
}
View
<button type="button" id="notifications"></button>
<script>
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
alert('success!');
}
});
});
</script>
EDIT: WORKING SOLUTION
Change the contents of the box above labeled "View" to the following:
<button type="button" id="notifications"></button>
<script>
(function ($) {
$(document).ready(function() {
$('#notifications').on('click', function() {
$.ajax({
url: '/notificationsSeen',
type: 'POST',
data: { _token: '{{ csrf_token() }}' },
success:function(){alert('success!');},
error: function (){alert('error');},
});
});
});
}(jQuery));
</script>
In your AJAX request, data is not a string. It is a key value pair. So use
data: { _token: '{{ csrf_token() }}' }
You shouldn't pass the csrf token like this:
data:'_token = <?php echo csrf_token() ?>',
You have to store it in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then automatically add the token to all request headers:
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data: {status: 'seen'},
success:function(data){
alert('success!');
}
});
});
});
Controller:
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => request()->input('status')));
return ['success' => true];
}

refresh data in view after ajax request symfony

I'am new in Ajax and I intregated one ajax request. The purpose is one user can like, unlike an article. Look my code :
controller
public function likeAction(Request $request, Article $article, $slug)
{
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
throw $this->createAccessDeniedException();
}
if ($request->isXmlHttpRequest()) {
$tokenStorage = $this->get('security.token_storage');
$currentUser = $tokenStorage->getToken()->getUser();
$likes = $article->getLikes();
foreach ($likes->getUsers() as $user) {
if ($user == $currentUser) {
throw new \Exception('Vous aimez déjà cet article !');
}
}
$likes->addUser($currentUser);
$likes->setCount($likes->getCount() + 1);
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
$count = $article->getLikes()->getCount();
return new JsonResponse(array('data' => $count));
}
return $this->redirectToRoute('pm_platform_view', array('slug' => $slug));
}
route
pm_platform_like:
path: /like/{slug}
defaults:
_controller: PMPlatformBundle:Article:like
view
<a class="btn btn-blue-grey" id="like" role="button"></a>
<span class="counter" id="counter">{{ article.likes.count }}</span>
<script>
$( document ).ready(function() {
$(document).on('click', '#like', function (e) {
$this = $(this);
$.ajax({
type: 'GET',
url: '{{ path('pm_platform_like', {slug: article.slug}) }}',
dataType: 'JSON',
data: {},
success: function() {
//refresh article.count here
}
});
});
});
</script>
Currently the ajax request works and the "like" is persisted in database. But in my view nothing change, I have to "refresh" data, more precisly the like count attribute of article entity after the success of the ajax request. I need help for that.
Assuming you have another ajax request that gets like count.
success: function(response) {
//Recall function here that gets like count.
fnGetLikeCount();
}
Edited:
Can you post that function/ajax request that gets like count?
Edit 2:
Yes you can send response from controller and can assign/set that count in like lable/div or what ever you are using.
Your AJAX request is already send total counts in response. So, all you need to update "counter" div with total like count.
objResponse holds response of ajax request and total like count would be stored inobjResponse.data .
success: function(objResponse) { // "objResponse" is response os ajax request
$("#counter").html(objResponse.data);
^^
}
Full Code
<a class="btn btn-blue-grey" id="like" role="button"></a>
<span class="counter" id="counter">{{ article.likes.count }}</span>
<script>
$( document ).ready(function() {
$(document).on('click', '#like', function (e) {
$this = $(this);
$.ajax({
type: 'GET',
url: '{{ path('pm_platform_like', {slug: article.slug}) }}',
dataType: 'JSON',
data: {},
success: function(objResponse) { // "objResponse" is response os ajax request
//refresh article.countcounter here
$("#counter").html(objResponse.data);
^^
}
});
});
});
</script>
Read more about ajax

Categories