Angel Miladinov
Angel Miladinov

Reputation: 1655

Laravel generate get route with parameters with data from ajax

I am sedindg an ajax request to get products like this:

$.ajax({
    url: '{{ route('filter-products') }}',
    type: 'POST',
    data: {_token: '{{ csrf_token() }}', filters: filters, category_id: {{ $category->id }} }
})
.done(function(products) {
    console.log(products)

    let html = ''
    for(product of products) {
        html += '<div class="col-md-4 women-grids wp1 animated wow slideInUp" data-wow-delay=".5s">' 
            html += '<a href="product-route-here">'

            html += '<div class="product-img">'
                html += 
            html += '</div>'

            html += '</div>'
            console.log(html)
    }
})
.fail(function() {
    console.log("error")
})
.always(function() {
    console.log("complete")
})

My Route :

Route::get('/product/{slug}', 'ProductController@show')->name('product');

The problem is with the <a href> which I need to generate for the product link in laravel when I print the products I will call it like this route('product', $product->id) but in that case how do I pass the product id to the route function to generate the link?

Upvotes: 0

Views: 3155

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

If you have id in product Change from

html += '<a href="product-route-here">'

To

html += '<a href="/product/"'+product.id+'>'

Also use termination sign colon ; at the end it will help if you are going to make minified js.

Upvotes: 2

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

If your ajax code is located on blade file then add below line in that view file. This line will generate url till product, then you can concat with your id in your ajax code.

<script>var product_url = "{{url(' / ')}}/product/";</script>

After adding above line use product_url variable in your ajax code like below code.

html += '<a href="' + product_url + product.product_id + '">'

Upvotes: 2

Related Questions