0
votes

I have this error on my browser console: "PUT http://localhost:8000/post/2 500 (Internal Server Error)"

I use resource Controller and my route- Route::resource('post','PostController');

Here resource controller code for update post:

public function update(Request $request, $id)
{
        $post = Post::findOrFail($id);
        $post->name = $request->name;
        $post->content = $request->content;
        $post->save();
        return response()->json($post);
}

Here my view code:

<form class="form-horizontal" role="form">
    <div class="form-group">
        <input type="text" class="none" id="id">
        <label class="control-label col-sm-2">Name:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="name">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2">content:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="content">
        </div>
    </div>
    <div class="form-group">
        <input type="submit" value="Edit" onclick="mainCatEdit();">
    </div>
</form>

Ajax code:

function mainCatEdit() {
    $.ajax({
        url: '/maincategory/'+id,
        type: 'PUT',
        data: {
            '_token': $('input[name=_token]').val(),
            'id': $('#id').val(),
            'name': $('#name').val(),
            'content': $('#content').val()
        },
        success:function(data) {
            console.log(data);
        }
    });
}

by the way i use meta token {{ csrf_token() }} on my file header. but i get 500 internal server error on localhost.so someone help me.

2
check your error logs. - Rotimi
also the id javascript variable doesn't seem to be defined anywhere - Rotimi
on view code i use id field. @Akintunde-Rotimi - Romi

2 Answers

0
votes

You forgot to fill the data to your model, do this:

public function update(Request $request, $id)
{
        $post = Post::findOrFail($id);
        $post->fill([
            $post->name = $request->name;
            $post->content = $request->content;
        ]);
        $post->save();
        return response()->json($post);
}
0
votes

you are trying to get the value of a token you did not set, lets look at your code again without testing, just try this set this at the top of your page under the meta tags

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

then your ajax should be

function mainCatEdit() {
$.ajaxSetup({
headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
    url: '/maincategory/'+id,
    type: 'PUT',
    data: {
        'id': $('#id').val(),
        'name': $('#name').val(),
        'content': $('#content').val()
    },
    success:function(data) {
        console.log(data);
    }
});

}

i hope this helps