I'm trying to set up ajax for laravel, but it won't work. I have controller for posting comments. javascript which blocks the submit button and sends ajax which is returning 500 error
public function postComment()
{
if (Request::ajax())
{
return Response::json(['blah' => 'ohhh']);
}
}
$('#submit_comment').click(function (e)
{
e.preventDefault();
$.ajax({
type : "POST",
url : "http://page.dev/posts/comment",
data :
{
comment : $("#comment_area").text()
}
});
});
<script type="text/javascript">var comment = "{{URL::action('PostsController@postComment')}}"; </script>
What it returns is 500 internal server error
UPD:
Route::get('posts/{id}', ['as' => 'post', 'uses' => 'PostsController@getShow'])->where('id', '\d+'); // Where id == number
Route::get('category/{id}', ['as' => 'category', 'uses' => 'PostsController@getCategory'])->where('id', '\d+');
SOLUTION: I used in constructor csrf protection. after i removed csrf protection from postComment it worked for me Route::controller('posts', 'PostsController');
It is difficult to to offer advice without seeing your route, controller, view code neatly separated. However, this is the bare minimum necessary to achieve your desired outcome:
In your routes.php
Route::post('/comment', function()
{
return Response::json(['blah' => 'ohhh']);
});
In your view:
$.ajax({
type : "POST",
url : "comment",
});
if you are getting a 500 response then it is likely that you have a problem with your route to controller@postComment.