A
A
axblue2016-11-24 00:44:57
Laravel
axblue, 2016-11-24 00:44:57

How to pass post ID on Ajax submit?

Good evening everyone. Tell me how you can pass the post id to the controller when sending ajax.
Can I do something through the route?
Here is AJAX

$('#recipe_comments').on('submit', function(e) {
    e.preventDefault();
    var text = $('.text').val();
    $.ajax({
        type: "POST",
        url: '/add_comment',
        data: {text:text},
        success: function(param)
        {
            console.log(param);
        },
        error: function(msg){
            console.log('error');
        }
    });
});

Route
Route::get('/add_comment', '[email protected]');

Everything works, but I can’t figure out how to pass the id of the post to which I am sending the comment text.
This is the address el-recipes/recipe/8 of the post itself, that is, I need to somehow catch and send id = 8 to the controller. I tried to prescribe {id} in the route and receive it in the controller, but something doesn’t work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WebDev, 2016-11-24
@leshikgo

Route::get('/add_comment/{id}', '[email protected]');

In the controller you get
public function addCommend($id)
{
    //$id - ваш id
}

V
Valeriu Vodnicear, 2016-11-24
@vodnicear

$('#recipe_comments').on('submit', function(e) {
    e.preventDefault();
    var text = $('.text').val();
    var id = 123;
    $.ajax({
        type: "POST",
        url: '/add_comment',
        data: {
             'id': id,
             'text':text
        },
        success: function(param)
        {
            console.log(param);
        },
        error: function(msg){
            console.log('error');
        }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question