Asm Arman Asm Arman - 2 months ago 22
PHP Question

Laravel ajax request not working for a foreach loop

I have collected some data in my controller.Now In my view,I have showed them inside an unordered list (ul) as a link.

<ul>
<li><a>....</a></li>
</ul>


Now When I am trying to fire an ajax request,only last data (i.e,Last link in listed items) is responding to the ajax request.The Ajax script is not inside the foreach loop.Do I have to place the ajax script inside the foreach loop.Then,for each data there will be a script.won't it create a problem?

<ul>
@foreach ($brands as $brand)
<li class='n1'><a href="{{$brand->id}}" id="{{$brand->brand}}">{{$brand->brand}}</a></li>
@endforeach
</ul>


my ajax script:

<script>

$('#{{$brand->brand}}').on('click',function(e){
e.preventDefault();

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

$.ajax({
type:"POST",
url:'/userproduct',
data: { value: $('#{{$brand->brand}}').attr('href')},
success:function(data) {
console.log(data);
}
});
});
</script>


In My Controller

public function userproduct(Request $request){
$value=$request->input('value');
return Response::JSON($value);
}

Answer

At first, made the following changes in a elements for example:

<a class="brand" href="{{url('userproduct')}}" data-id="{{$brand->id}}">
    {{$brand->brand}}
</a>

Then use the following code:

$(document).ready(function() {

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('a.brand').on('click',function(e) {
        var el = $(this);
        $.ajax({
            type: "POST",
            url: el.attr('href'),
            data: { value: el.attr('data-id')},
            success: function(data) {
                console.log(data);
            }        
        });

        e.preventDefault();
    });
});

This should work but make sure that, you've also declared a route using post method for userproduct, for example:

Route::post('/userproduct', 'SomeController@handlerMethodName');

Check the browser console to find out error details if it doesn't work and try to solve the issues.The workflow is okay and should work if everything went well.


Note: There are other ways to do it (using different code/approach) but this is a simplified code depending on your code given in the question. For example, I could have used the ul to register the event handler using event delegation but this'll work as well.