mostafiz13 mostafiz13 - 4 months ago 23
Javascript Question

call route from button inside an <a> tag laravel

I'm new in laravel and Javascript.

I have a route which looks like

Route::get('/problems/{problem}/edit', 'AdminController@editProblem');


and my page looks like
image

HTML code for this page is

@foreach($in_contest->problems as $problem)
<div class="list-group">
<a href="#" class="list-group-item">
<i class="fa fa-file fa-lg"></i>
{{ $problem->title }}
<span class="pull-right">
<button onclick="callRoute()" class="btn btn-xs btn-info button">Edit</button>
</span>
</a>
</div>
@endforeach


I wrote javascript code for this onclick which is

<script type="text/javascript">
function callRoute() {
window.location = '{{ url('/problems/' . $problem->id . '/edit') }}';
}
</script>


now every time I'm clicking Edit button on P1, P2, or P3 its opening the edit page for P4. Same url is opening for all.
I want when I click edit on P1 its redirect to edit page for $problem-id with P1. and same for the others too.

What is the solution of this problem ?

Answer

The reason it is calling p4 is that after you have run your foreach loop, you are basically writing the last iteration of problem ID to your javascript.

You can avoid adding blade syntax to your javascript all together by changing your view code to the following so it passes the current problem ID to your javascript function

@foreach($in_contest->problems as $problem)
    <div class="list-group">
        <a href="#" class="list-group-item">
            <i class="fa fa-file fa-lg"></i>
            {{ $problem->title }}
            <span class="pull-right">
                <button onclick="callRoute({{ $problem->id }})" class="btn btn-xs btn-info button">Edit</button>
            </span>
        </a>
    </div>
@endforeach

and your javascript function to the following

<script type="text/javascript">
    function callRoute(problemID) {
        window.location = '/problems/' + problemID + '/edit';
    }
</script>