0

<?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

5
  • is there any JS error in the console? Commented Nov 29, 2018 at 17:13
  • Uncaught SyntaxError: Unexpected token ; in this line 'X-CSRF-TOKEN':$('meta[name="_token"]').attr('content'); Commented Nov 29, 2018 at 17:16
  • also $.ajaxSetup part should be included in your layout file, not inside onclick event handler. and do you have <meta name="csrf-token" content="{{ csrf_token() }}"/> in your layout's file head section? Commented Nov 29, 2018 at 17:17
  • one more comment from me is that whenever you are modifying the database it should be a POST, not GET request, though it's not what;s causing your error, just a rule to remember and follow ;) Commented Nov 29, 2018 at 17:18
  • can you please tell me what to edit in my code clearly and thank you for your time Commented Nov 29, 2018 at 17:21

1 Answer 1

1

In your resources/views/layouts folder, the main layout file should have those two elements to prevent CSRF attacks.

<!DOCTYPE html>

...

  <meta name="csrf-token" content="{{ csrf_token() }}"/> 

...

</head>
<body>

    ...

    <script type="text/javascript">
      $.ajaxSetup({
         headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
      });
    </script>

...

</body>

Also you need to remove this second part ($.ajaxSetup) from your onclick event handler. so it looks like this:

<script>
 $(document).ready(function(){
      $("#btnadd").on('click',function(e){

        e.preventDefault();

           $.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);
            }
        });
    });
  });

Sign up to request clarification or add additional context in comments.

2 Comments

You are kinggg maan
happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.