user3353610 user3353610 - 3 months ago 13
Javascript Question

On button click i want to display record from database laravel 5.2

I have a a a list that has a foreach loop.

<?php $i = 0?>
@foreach ($cards as $card)
<li id="{{$i}}"><a href="#">{{$card->title}}</a></li>
<?php $i = $i + 1; ?>

Based on id i want to display card->id when i click the link I want to display that specific cards's id.

var myvar='<?php echo json_encode($cards);?>';

for(var i=0;i<myvar.length;i++)
$( "#"+i ).click(function() {
alert( myvar );



Because you fetch already the data in your foreach loop we will just hide the user name inside the following div of every link then we will show it when the user click on the link, so we don't have to make connection to the database every time the user click.

You have to add class to your link my-link and add div where you want to show the name .name to your view :

view code:

    @foreach(User:all() as $user)
             <a href='' class='my-link'>{{$user->id}}</a>
             <div class='name' style="display: none">{{$user->name}}</div>

The add javascript code that attach the click event to the buttons with class my-btn.

JS code :

    $('body').on('click', 'my-link', function(e){


NOTE : make sure you're including jquery library in your code.

Hope this helps.