Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
20yco Avatar asked Dec 13 '25 06:12

20yco


1 Answers

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.

like image 66
Ben Claar Avatar answered Dec 15 '25 19:12

Ben Claar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!