405 Method Not Allowed - (1/1) MethodNotAllowedHttpException in Laravel 5 - laravel-5

Hi i have this delete button which i really want to pass using ajax call. My problem is that when the delete button is clicked this is the error that i get
NetworkError: 405 Method Not Allowed and (1/1) MethodNotAllowedHttpException. This is my code below
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
Im using the action('AddRecordController#destroy', $post['id']) since my AddRecordController is being generated. And my route is only this one
Route::resource('addRecord', 'AddRecordController');
My AddRecordController code below
public function destroy($id){
//
echo "Test";
echo $id;
$addRecord = Addrecord::find($id);
$addRecord->delete();
}
Can someone help me figured this thing out? Any help is muchly appreciated.
TIA.

You need to use the DELETE method. You can use form method spoofing to do this.
Try this:
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id,
"_method": "delete"
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>

Related

How to Refresh Table after ajax request in laravel

I am working on exchange project using laravel and want to refresh my table after a
<tbody class="fixed-header">
#foreach($transactionsCustomer as $transaction)
<tr>
<td>{{ $transaction->description }}</td>
#foreach($accounts as $account)
#if($transaction->code == 0)
#if($account->currency->id==$transaction->currency_id)
<td>{{ $transaction->amount }}</td>
<td></td>
#else
<td></td>
<td></td>
#endif
#else
#if($account->currency->id==$transaction->currency_id)
<td></td>
<td>{{ $transaction->amount }}</td>
#else
<td></td>
<td></td>
#endif
#endif
#endforeach
<td><a href="{{ route('transaction.edit',$transaction->id)}}" class="btn btn-primary" >سمون</a></td>
</tr>
#endforeach
</tbody>
and here is my ajax code to store the data
$("#transaction-form").submit(function(stay){
var formdata = $(this).serialize(); // here $(this) refere to the form its submitting
$.ajax({
type: 'POST',
url: "{{ route('transaction.store') }}",
data: formdata, // here $(this) refers to the ajax object not form
success: function (data) {
$('input[type="text"],textarea').val('');
updateTable();
},
});
stay.preventDefault();
});
and here is my controller method to represent the data
public function singleCustomer(Request $request)
{
$customer = Customer::find($request->id);
$accounts = Account::where('customer_id', $request->id)->get();
$currencies = Currency::all();
$transactionsCustomer = DB::table('transactions')->
join('accounts','transactions.account_id' ,'=','accounts.id')->join('customers','accounts.customer_id','=','customers.id')->join('currencies','accounts.currency_id','=','currencies.id')->select('transactions.*','currencies.id as currency_id')->where('customers.id',$request->id)->get();
return view('transaction.index',compact('currencies','customer','accounts','transactionsCustomer'));
}
now i want to refresh my table after this ajax request
You need to separate the table in different view.
Here's the flow, you get all data from your Controller , pass it to the table view, in the main view you include the table view using #include('table-view-route').
And don't forget on your success ajax, call updateTable() which has functionality to load the table view using jquery
$("#tableContainerId").load("{{url('table-view-route')}}");

How to prevent ajax request before clicking on OK button of onclick="confirm(' ')" message?

$(document).ready(function(){
$(document).on('click', '.dlt', function () {
var id = $(this).attr('data-id');
var token= '{{ csrf_token() }}';
$.ajax({
method: 'post',
url: '{{route('product.delete')}}',
data: {id:id, _token:token},
success: function (response) {
location.reload();
}
});
});
});
<tbody>
#if($products->count()>0)
#foreach($products as $product)
<tr>
<td class="p_name">{{$product->name}}</td>
<td class="p_details">{{$product->details}}</td>
<td class="p_price">{{$product->price}}</td>
<td><a class="add" data-id="{{$product->id}}" title="Add" data-toggle="tooltip" style="display: none"><i class="fa fa-book"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="fa fa-edit"></i></a>
<a class="dlt" onclick="confirm('Are you sure to delete it?')" title="Delete" data-toggle="tooltip" data-id="{{$product->id}}"><i class="fa fa-trash"></i></a>
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="4" class="text-center bg-danger">No Product Data Found</td>
</tr>
#endif
</tbody>
Although I click on Cancel button of Confirm() message, but onclick ajax request already done. How to prevent it until I click on OK button of confirm() message?
Inside a function, you have to use this script -
var result = confirm("Want to delete?");
if (result) {
//Logic to Ajax
}
In your code
$(document).ready(function() {
$(document).on('click', '.dlt', function() {
var result = confirm("Want to delete?");
if (result) {
//logic to AJAX
var id = $(this).attr('data-id');
var token = '{{ csrf_token() }}';
$.ajax({
method: 'post',
url: '{{route('
product.delete ')}}',
data: {
id: id,
_token: token
},
success: function(response) {
location.reload();
}
});
}
});
});

Cannot read property replace of null method parameter

I started messing around with Vue.js earlier this week.
So far I created a list of MTG(a TCG) cards. The data comes from the database through an Ajax request. This all works like a charm.
What i want to do next is replace the string that contains the costs of a card e.g. something like '{1}{U}{G}' with images for the corresponding tag.
HTML:
<div v-for="(cards, key) in mainBoard" class="">
<table class="table">
<tr>
<th colspan="5">#{{ key }}</th>
</tr>
<tr>
<th>#</th>
<th>Name</th>
<th>ManaCost</th>
#if($deck->enableCommander())
<th>Commander</th>
#else
<th></th>
#endif
<th>Actions</th>
</tr>
<tr v-for="card in cards">
<td>#{{card.pivot.quantity}}</td>
<td>#{{card.name}}</td>s
<td v-html="replaceManaSymbols(card)"></td>
#if($deck->enableCommander())
<td>
<span v-if="card.pivot.commander" #click="preformMethod(card, 'removeCommander', $event)"><i class="fa fa-flag"></i></span>
<span v-else #click="preformMethod(card,'assignCommander', $event)"><i class="far fa-flag"></i></span>
</td>
#else
<td> </td>
#endif
<td>
<button #click="preformMethod(card,'removeCardFromDeck', $event)"><i class="fa fa-times-circle"></i></button>
<button #click="preformMethod(card,'plusCardInDeck', $event)"><i class="fa fa-plus-circle"></i></button>
<button #click="preformMethod(card,'minusCardInDeck', $event)"><i class="fa fa-minus-circle"></i></button>
</td>
</tr>
</table>
</div>
Vue.js
new Vue({
el: '#Itemlist',
data: {
mainBoard: [],
sideBoard: [],
},
methods:{
preformMethod(card, url){
var self = this;
var varData = {
slug: '{{ $deck->slug }}',
card: card.id,
board: card.pivot.mainboard
};
$.ajax({
url: '/vue/'+url,
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
},
replaceManaSymbols(card){
var mc = card.manaCost;
var dump = mc.replace(/([}])/g, '},').split(',');
var html = '';
/**
* replace each tag with an image
*/
return html;
}
},
mounted(){
var self = this;
var varData = {
slug: '{{ $deck->slug }}'
};
$.ajax({
url: '/vue/getDeckList',
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
}
})
I pass the card as a parameter to the replaceManaSymbols method. I can console.log the contents of mana without any issue. But as soon as a want to modify the string Vue throws the error TypeError: Cannot read property 'toLowerCase/split/replace' of null. I'm not really sure what's going wrong. Any idea's?
As a rule of thumb, you shouldn't use methods on the display side. Keep them for the update side - processing changes back into a store and such. Methods aren't reactive - they need to be called. You want your display to automatically reflect some underlying data, so you should use computed.
You should also avoid using v-html, because you end up with markup outside your templates, and that markup is static. It's not totally clear to me what will be in v-html, but you should try and keep markup in your template, and inject values using data, props or computed. Hope this helps!
If you want a div with some text that magically turns into an image tag, this could be a good use for <component :is>.

Update paginator laravel in ajax

I create a page on which there is a table with a paginator. I post a request to specify the output of rows from the database for insertion into the table. However, the paginator remains old. How should I change it?
Get a request for a new page or insert all the HTML code that comes from the controller is not satisfied.
Code view:
<table class="table table-bordered text-center table-hover" id="table_list">
<thead>
<tr>
<th>id</th>
</tr>
<tr>
<td><input type="text" class="form-control" id="id_card" value=""></td>
</tr>
</thead>
<tbody>
#if($dats)
#foreach($dats as $data)
<tr>
<td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table
Js code in view:
$('#id_card').on('keyup', function(){ // search
value = $(this).val();
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}'
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data); // update table
//update paginator links
},
error: function(data){
console.log(data);
}
})
})
Code controller
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
print($str);
return;
}
In Laravel 5, you could do it by changing your controller to something like this.
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
return response()->json([
'rows' => $str,
'links' => $models->render()
], 200);
}
In your ajax response, render the links with $('ul.pagination').replaceWith(data.links);
eg.
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}',
page: page
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data.rows); // update table
$('ul.pagination').replaceWith(data.links); // update links
},
error: function(data){
console.log(data);
}
});

Cannot access id being passed in vue.js and laravel

I am having hard time inserting the values which is the id that is being passed from the form into the controller of my enrollment system. To achieve this I make use of vue.js and vue-resource library. In my all.js file I am gettting the correct id value when I console.log the id being passed. However, when passing it to the route address of my application I am getting 500 error. Also, upon debugging I' m getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'section_subject_id' cannot be null (SQL: insert into reservations. How can I solve this?
ReservationController.php
class ReservationController extends Controller
{
public function create($id)
{
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects'));
}
public function store(Request $request)
{
$subject = new Reservation();
$subject->section_subject_id = $request->input('id');
$subject->student_id = 1;
$subject->save();
}
}
all.js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#app-layout',
data: {
subject: {
id : ''
},
subjects: []
},
ready: function(){
},
methods:{
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', id, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}
}
});
form.blade.php
<body>
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id }} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
Try formatting the data being sent like this: {id: this.id}
So your Vue addSubject Method looks like this:
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', {id: this.id}, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}

Resources