Friday, April 27, 2018

Ajax 405 error and laravel MethodNotAllowedHttpException - development

Ajax 405 error and laravel MethodNotAllowedHttpException

I’m learning laravel now, and I need to know how to update database by AJAX, but I have a problem. When i click button i show on console 405 erorr and next laravel MethodNotAllowedHttpException. But database is updated after this. What’s wrong?

My .js:

var postId = 0;
jQuery.support.cors = true;

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('.post').find('.interaction').find('.edit').on('click', function(event) {
    event.preventDefault();

    var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
    postId = event.target.parentNode.parentNode.dataset['postid'];
    $('#post-body').val(postBody);
});

$('#modal-save').on('click', function() {
    $.ajax({
        method: 'post',
        type: 'post',
        url: url,
        data: {body: $('#post-body').val(), postId: postId, _token: token}
    }).done(function (msg) {
        console.log(msg);
    });
});

my route:

Route::post('/update', [
        'uses' => 'PostController@update',
        'as' => 'post.update',
    ]);

and controller:

public function update(Request $request){

        $this->validate($request, [
            'body' => 'required'
        ]);
        $post = Post::find($request['postId']);
        if (Auth::user() != $post->user) {
            return redirect()->back();
        }
        $post->body = $request['body'];
        $post->update();
        return response()->json(['message' => $post->body], 200);
    }

//Edit

I try to change url to ‘/update’ but it’s the same, database is updated, but i see a laravel error.



from Laravel Questions and Answers https://laravelquestions.com/php/ajax-405-error-and-laravel-methodnotallowedhttpexception/
via Lzo Media

No comments:

Post a Comment