when i click delete all selected its saying undefined variable however when i check the database the post gets deleted and when i refresh the page the post gets removed from the page. I don't understand why its bringing an error when its working.
blade
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
Delete All Selected
post Name
post Details
Action
#foreach($posts as $key => $post)
id}}">
id}}">
{{ ++$key }}
{{ $post->about }}
{{ $post->image }}
id}}" class="btn btn-danger btn-sm"
data-tr="tr_{{$post->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">
Delete
#endforeach
<script type="text/javascript">
$(document).ready(function () {
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
} else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".sub_chk:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
</html>
```
controller
public function showem(Post $post)
{
$posts = Post::get();
return view('users.registered', compact('posts'));
}
public function deleteAll(Request $request)
{
$ids = $request->ids;
$deleted = Post::whereIn('id',explode(",",$ids))->delete();
return view('users.registered');
}
After review your full question again and again, I found that you have got this error on detele method.
You need to send posts variable also on delete method :
public function showem(Post $post)
{
$posts = Post::get();
return view('users.registered', compact('posts'));
}
public function deleteAll(Request $request)
{
$ids = $request->ids;
$deleted = Post::whereIn('id',explode(",",$ids))->delete();
$posts = Post::get();
return view('users.registered', compact('posts')); // here send the posts variable
}
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>
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() }}">
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");
}
});
In my laravel project, i want to refresh my page after an ajax success but my page would refresh after the success. I tried to refresh with laravel redirect in the controller and it didn't work, i have also tried to refresh in the ajax and nothing happened? How do i do this right? How do i do this right?
Controller
if(request()->ajax()) {
//do something
return ['success' => 'successfully done'];
return redirect('admin/all')->with('status','Successfully done!');
JS
<script type="text/javascript">
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.approve_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
window.location.href="/your/url" ;
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
You need to use javascript to refresh the page. You can use location.reload()
if ( data['success'] )
{
alert(data['success']);
location.reload();
}
For those of you still looking for a Solution, This is how you can resolve this issue.
First of all, just return a simple message in your controller.
class SettingsController extends Controller
{
public function __construct()
{
}
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return 'Record successfully deleted';
}
}
Secondly, Add this code in your javascript file to refresh the page.
setTimeout(function () { document.location.reload(true); }, 5000);
<script type="text/javascript">
function deluser(id)
{
event.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:"{{ route('settings.destroy','')}}/"+parseInt(id),
method: 'delete',
data:{
id: id,
},
success: function(data)
{
$('#validation-message').append('<div class="alert dark alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+data+'</b></div>');
setTimeout(function () { document.location.reload(true); }, 5000);
},
error: function(xhr)
{
$('#validation-message').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-message').append('<div class="alert dark alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+value+'</b></div>');
});
}
});
}
</script>
Finally in your HTML.
<!DOCTYPE html>
<html>
<body>
<div class="col-xl-12 form-group" id="validation-message"></div>
<button onclick="deluser('ID_NUMBER_GOES_HERE')">Click me</button>
</body>
</html>
You can try something like this
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
}
Is there a way to update a database using 1 click?
i.e
echo "<a href='".$wpdb->query(" UPDATE partners SET active='no' WHERE partner_id='$active_partner->partner_id' ")."'>Disable</a>";
You need to react on a click with an ajax function.
i.e.
$('#your_button_id').bind('click', function () {
function_with_ajax();
})
function function_with_ajax() {
$.ajax({
here you could call the update.php script and transmit dynamic data
});
}
<button id="btn-save" type="button">
save
</button>
<script type="text/javascript">
jQuery(document.ready(function ($) {
$("#btn-save").click(
function () {
$.ajax({
type:"POST",
url:"/wp-admin/wp-ajax.php",
data:{
action:"save_data",
data:"data-update",
condition:"data-condition"
},
success:function (response) {
console.log(response);
},
error:function (error) {
console.log(error);
}
})
}
);
}))
</script>
and add to file function:
add_action("wp_ajax_save_data",function ()
{
global $wpdb;
$wpdb->update("your-table",
["your_field" => $_POST['data']]
,["condition-filed"=>$_POST['condition']]);
});