Laravel - load post with custom id via ajax

I want to load my post via AJAX, when I click on the post link, how can I send my post ID via AJAX?

I have a link in my Blade file:

{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}

      

I have the following route definition:

Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController@show']);

      

And the controller action:

public function show($id, $slug = null)
{
    $post = $this->news->getById($id, 'news');

    if ($slug != $post->slug){
     return Redirect::route('news', ['id' => $post->id, 'slug' => $post->slug]);
    }

    Event::fire('posts.views', $post);

    return View::make('post/post', compact('post'));
}

      

And then I try this:

var postTitle = $(".link--to--post");

postTitle.click(function () {   
    $.ajax({
        url: '/news/{id}-{slug}',
        type: 'GET',
        data: $(this),
        success: function (data) {
            console.log(data)
        }      
    });

    return false;
});

      

But it doesn't work for me, what am I doing wrong?

+3


source to share


1 answer


Your javascript should pass parameters like this:

$.ajax({
    url: '/news/' + id + '-' + slug,
    success: function (data) {
        console.log(data)
    }      
});

      



You had url: '/news/{id}-{slug}'

one that would issue a GET request to /news/{id}-{slug}

which is not a valid route - you need a url for example /news/1-foo

.

+2


source







All Articles