<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class categorycontroller extends Controller
{
public function display()
{
$cat=Category::all();
return view ('category',['cat'=>$cat]);
}
public function add(Request $request)
{
Category::create([
'Name' =>$request->name
]);
return response()->json(['success'=>'Data is successfully added']);
}
}
Route::get('/category','categorycontroller@display');
Route::get('/category/add','categorycontroller@add');
@extends('layout1')
@section('content')
<form id="myform">
<div class="form-group">
<!--<label for="name">Name :</label>-->
<table class="table table-bordered">
<thead><tr><th>Category</th><th colspan="2" align="center">Action</th></tr></thead>
<tbody>
</div>
@foreach($cat as $c)
<tr id='cat_{{$c->id}}'>
<td><input type="text" class="form-control" id="name_{{$c->id}}" value="{{$c->Name}}"></td>
<td><button class="btn btn-primary" id="btnupdate_{{$c->id}}" onclick="updatecat({{$c->id}})">Update</button></td>
<td><button class="btn btn-primary" id="btndelete_{{$c->id}}" onclick="deletecat({{$c->id}})">Delete</button></td>
</tr>
@endforeach
</tbody>
<tr><th colspan="2">New Category</th></tr>
<tr><td>
<div class="form-group">
<input type="text" class="form-control" id="name_0" value="">
</div>
</td>
<td>
<button class="btn btn-primary" id="btnadd">Add</button>
</td>
</tr>
</table>
</form>
<script type="text/javascript" src="{{asset('js/jquery.js')}}"></script>
<script>
$(document).ready(function(){
$("#btnadd").on('click',function(e){
e.preventDefault();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN':$('meta[name="_token"]').attr('content');
}
});
$.ajax({
url:"{{url('category/add')}}",
method:'get',
data:{
name:$('#name_0').val()
},
success:function(result)
{
$('.alert').show();
$('.alert').html(result.success);
//$('#tbcat').append(result.row);
}
});
});
});
</script>
@endsection
I write this code to display categories in the table from the database, it worked successfully. then I added ajax jquery code to add category to the database and display it after added to the table in the form. I wrote my codes in a blade.php and in the route and I used class category and category controller but when I click add button it's doesn't work successfully. Please can anyone help me to correct the error h