Hey guys I'm using laravel 5.7 and I'm attempting to make a ajax post request to update my database. The ajax would post based on a checkbox on change function. Example if i toggle off the checkbox it would send a request and update my status to Inactive in my User table. After attempting it, i had an error of 405 (Method Not Allowed). Anyone able to note what am i doing wrong? Sorry if there are some wrong codes or syntax in my codes as I'm very new to Ajax. Any help would be appreciated.
Ajax
$(document).ready(function(){
$.ajax({
type:'get',
url:'{!!URL::to('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
console.log(checkBox);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(){
$.ajax({
type: "POST",
url : '{!!URL::to('admin/{admin}')!!}',
success:function(data){
console.log(data);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
});
Route
Route::resource('admin','AdminController'); << I'm using the update method from the resource controller
Controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
Form
{!!Form::open(array('action'=>['AdminController#update',$item->u_id],'method'=>'POST','id'=>'update'))!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="u_id" id="u_id" value="{{$item->u_id}}">
<label class="custom-control custom-checkbox">
<input type="checkbox" id="switch-{{$item->u_id}}" class="custom-control-input">
<span class="custom-control-indicator"></span>
</label>
{{-- <button class="btn btn-primary">Update</button> --}}
{{Form::hidden('_method','PUT')}}
{!!Form::close()!!}
UPDATE
I have managed to "pass" the u_id to my post request by getting the id through target.id and splitting it with -. It is not the most elegant way but it works. But now im getting an error
POST http://manageme.test/admin/%7B2%7D 500 (Internal Server Error)
Here is what i have updated in my codes.
$('#switch-'+data[i].u_id).change(function(e){
console.log(e.target.id);
var s = e.target.id;
var split = s.split('-')[1];
$.ajax({
type: "POST",
url: `{!!url('admin/')!!}/{${split}}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success:function(data){
console.log(data);
}
});
});
these are inside my update controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
I have also looked at the error inside the network tab of the dev tools the error message from laravel is message: "Trying to get property 'status' of non-object". I think it cant find any $user inside the update method
Instead of:
"{!!URL::to('admin/{admin}')!!}"
write :
`{!!url('admin/')!!}/${data[i].u_id}`
and add _token and _method params to your ajax data
and write like this:
$(document).ready(function () {
$.ajax({
type: 'get',
url: '{!!url('findStatus')!!}',
success: function (data) {
data.forEach(d => {
console.log(d);
if (d.status == "Active") {
$(`#switch-${d.u_id}`).prop('checked', true);
}
else if (d.status == "Inactive") {
$(`#switch-${d.u_id}`).prop('checked', false);
}
$(`#switch-${d.u_id}`).change(function () {
console.log(d);
//changed###########
$.ajax({
type: 'POST',
url: `{!!url('admin/')!!}/${d.u_id}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success: function (data) {
console.log(data);
}
});
//###################
});
});
},
error: function (data) {
console.log('ERROR');
}
});
});
Solution
I managed to fix it the problem was coming from the route trying to pass the u_id of the user and finding the user's data. So instead of typing the url inside, i made a variable to pass the route and u_id together. Here are the codes
Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'get',
url:'{!!url('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(e){
var s = e.target.id;
var split = s.split('-')[1];
var url = '{{route('admin.update','split')}}';
$.ajax({
type: 'POST',
url: url,
data: { _token: "{{ csrf_token() }}", _method: "PUT" ,u_id: split},
success: function(data) {
console.log(data['message']);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
Update method
public function update(Request $request, $id)
{
$user = User::find($request['u_id']);
if($user->status == "Active")
{
$user->status = "Inactive";
$user->save();
return response()->json(['message' => 'Update to Inactive']);
}else{
$user->status = "Active";
$user->save();
return response()->json(['message' => 'Update to Active']);
}
}
DONT forget to add the meta tag onto the document header for csrf token
<meta name="csrf-token" content="{{ csrf_token() }}">
Related
I update the database with jquery ajax and print "success/failure" with alert according to the return value. The product update is successful, but the message "failed" appears on the screen and I get the error "The PUT method is not supported for this route".
My jquery:
$('#policies_button').on('click', function () {
$('#ShiftAddModal').modal('hide');
var id = $('#select_policies').val();
var url = $('#selected_option_' + id).attr('data-url');
$.ajax({
type: 'PUT',
data: $('#bulkupdate_form').serialize(),
url: url,
success: function (response) {
if (response.success) {
$('#ShiftAddModal').modal('hide');
alertify.success('Başarılı: İzin kuralı ataması başarılı bir şekilde gerçekleşmiştir.');
} else if (response.error) {
alertify.error(response.error);
}
},
error: function (e) {
alertify.error('Hata: Sayfanızı yenileyerek tekrar deneyiniz.');
}
});
});
url:
<option id="selected_option_{{$item->policies_id}}"
value="{{$item->policies_id}}"
data-url="{{route('personnel.update',$item->policies_id)}}">{{$item->name}}</option>
coming here by route:
protected function policiesAction(Request $request, $id)
{
foreach ($this->model->get() as $item) {
$action = Actions::personnel_policies_update(
$this->model,
$request->get('personnel_name' . $item->personnel_id),
$id
);
}
return $action;
}
public static function personnel_policies_update(Model $model,$personnel_id,$id){
$fields = array(
'policies_id' => $id,
);
$model->where('personnel_id',$personnel_id)->update($fields);
return redirect()->to(route('bulkupdate.index'))->with('success','Başarılı: Personel ataması başarıyla gerçekleşti!');
}
Change the method to POST.
$.ajax({
type: 'POST',
data: $('#bulkupdate_form').serialize(),
url: url,
...
});
Considering that csrf token is not been included in the headers yet, you must include it on form data:
<form id="bulkupdate_form" ... >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<!-- or simply -->
#csrf
</form>
I am working with Laravel Datatable and I have stuck in one point. Below code for delete the entry in the TagManagement model. But it isn't delete the entry and worse thing is it didn't show any error. Can anybody find the error in below code?
view
$(document.body).on("click",".remove-tag", function () {
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
Controller
public function destroy($id)
{
$tagManagement = TagManagement::find($id);
$deleted = $tagManagement->delete();
if ($deleted) {
return "SUCCESS";
} else {
return "FAIL";
}
}
public function loadTags()
{
$Tags = TagManagement::all();
return DataTables::of($Tags)
->addColumn('action', function ($tag) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $tag->id . '" class="btn btn-default remove-tag remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
}
**Route**
Route::get('/delete-tag', 'AdminPanel\TagController#destroy');
Your route and controller method don't seem to correspond. First of all, it is better to use the "delete" HTTP request method for delete actions, but this is not what is causing your problem.
You defined your route as /delete-tag but in your controller you expect an $id as a parameter to your destroy method. In order for that to work you would need to have the route like this /delete-tag/{id} and construct the URL for your ajax call correspondingly on the frontend. I'm surprised you don't get the Missing argument 1 for App\Providers\RouteServiceProvider::{closure}() exception for malforming your request this way.
Laravel documentation explains very well how to define routes with parameters.
It would be helpful if you included Laravel version in your question.
Here is how it should work:
Route definition
Route::delete('/delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('delete-tag');
JS function
function deleteTag(id){
let route = '{!! route('delete-tag', ['id' => '%id%']) !!}';
$.ajax({
type: 'post',
url: route.replace('%id%', id);,
data: {_method: 'delete'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
It is not your Datatable problem, you missed some code, you did not define route & jQuery function properly, your destroy($id) function received a parameter but you do not receive any parameter in your route & you not send _token in your ajax action you need to send _token
Check My code I am edited your code.
//Change your Route
Route::get('delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('deleteTag');
//Change your function
function deleteTag(id){
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('deleteTag', '') }}/'+id,
data: {_token: '{{csrf_token()}}'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
I'm trying to run an ajax call, and i keep getting
http://127.0.0.1:8000/books/rate/2 404 (Not Found)
So it gets the id well, but showing a 404 error.
route.php
Route::post('rate/{book_id}','BookController#rate')->name('rate');
main.js
$('#sub').submit(function(e){
var owl = $(this).attr("data");
var route = JSON.parse(owl);
$.ajax({
type:"POST",
url:"rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(res){
console.log("owls");
}
});
event.preventDefault();
});
controller(book controller)
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return redirect()->back()->with("status", "You already left a review");
}
}
HTML
<form id="sub" data= "{{ $book }}">
{!! csrf_field() !!}
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}"> ></div>
<input name="rating" value='{{ $book->userSumRating or 0 }}' type="hidden" id="val">
<button type="submit" class="btn btn-primary mt-2">submit</button>
</form>
You are using ajax post so instead redirect use json response like this
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => "You already left a review"]);
}
}
Add try this javascript code
$.ajax({
type:"POST",
url:"http://127.0.0.1:8000/rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{rating: $('#val').val()},
success:function(res){
console.log("owls");
}
});
I think you need a change in javascript like below
$('#sub').submit(function(e){
var owl = $(this).attr("data");
var route = JSON.parse(owl);
$.ajax({
type:"POST",
url:"http://127.0.0.1:8000/rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(res){
console.log("owls");
}
});
event.preventDefault();
});
This is because in your URL you are getting books before rate/{rate_id} thats why it is showing error of 404 page not found!
Just Use It Like This :-
$.ajax({
type:"POST",
url:"{{url('rate/')}}" + route.id,
headers: {
'X-CSRF-TOKEN': {{ csrf_token() }}
},
success:function(res){
console.log("owls");
}
});
I know there are similar questions relating to this issue, but I have tried my copy after those with the right answer, yet still to no avail.
I keep getting this error:
BadMethodCallException Method delete does not exist. in Macroable.php (line 74)
To be quick, here is my controller:
public function destroy(Subject $subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
Here is my route:
Route::delete('/subjects/delete/{subject}', 'SubjectsController#destroy');
Here is my view:
<td>
<a data-token="{{ csrf_token() }}" id="delete" data-id="{{$subject->id}}" data-toggle="tooltip" title="Edit" href="/subjects/{{$subject->id}}" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>
</td>
and last my scripts:
$(document).on('click', '#delete', function(event) {
event.preventDefault();
/* Act on the event */
// id of the row to be deleted
var id = $(this).attr('data-id');
var token = $(this).data("token");
console.log(id);
// row to be deleted
var row = $(this).parent("td").parent("tr");
var message = "subject";
bootbox.dialog({
message: "Are you sure you want to Delete this "+message+"?",
title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data: {
"id": id,
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
}
}
});
});
Here is what I get when I don php artisan route:list
I don't know the technical details of why it is working this way but it seems the the problem was coming from my controller destroy method. So, this was all I had to do:
controller code:
public function destroy($subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
script:
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data:{"id": id, "_method": 'DELETE'}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
route:
Route::delete('/subjects/delete/{subject}','SubjectsController#destroy');
The main thing for me was to remove the Subject from the destroy() parameter and it work.
If any of you know why it's working that please provide and explanation so that I can understand it too. Thanks!!
Change the type in your ajax call to POST, the _method field in the data object is all that is needed. This is how your ajax call should look. Laravel "fakes" the DELETE method by using the _method field to determine the http verb.
$.ajax({
type: 'POST',
url: '/subjects/delete/'+id,
data: {
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
I want to toggle a boolean value in my table with a checkbox through jquery and ajax.
So whenever a user ticks the the checkbox it should toggle the value in table.
So far i came up with this but i need help:
$(document).ready(function(){
$("input:checkbox").change(function() {
var isChecked = $("input:checkbox").is(":checked") ? 1:0;
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: $('.checkbox').serialize(),
success:function(data){
}
});
});
});
#andre's answer is correct but
if($user->active == 1){
$user->active = 0;
} else {
$user->active = 1;
}
this part can be done by a single line
$user->active = !$user->active;
The only thing I'd modify would be returning an answer to the ajax call to let it know what's happening.
public function activation(Request $request)
{
$user = User::findOrFail($request->user_id);
if($user->active == 1){
$user->active = 0;
} else {
$user->active = 1;
}
return response()->json([
'data' => [
'success' => $user->save(),
]
]);
}
And now in the front-end part:
$(document).ready(function(){
$("input:checkbox").change(function() {
var user_id = $(this).closest('tr').attr('id');
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "user_id" : user_id },
success: function(data){
if(data.data.success){
//do something
}
}
});
});
});
jQuery Ajax documentation
in model create a method
function toggleActive ()
{
$this->active!=(int)$this->active;
return $this;
}
in controller
$model->toggleActive()->save();