20yco
20yco

Reputation: 906

Laravel - load post with custom id via ajax

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

I've got 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've got the following route definition:

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

And 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'm trying 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 this doesn't work for me, what am I doing wrong?

Upvotes: 3

Views: 2225

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

Your javascript should pass the parameters like this:

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

You had url: '/news/{id}-{slug}', which would perform a GET request to /news/{id}-{slug}, which isn't a valid route -- you want a URL like /news/1-foo.

Upvotes: 3

Related Questions