How to get id from modal to ajax request in laravel?

Viewed 666

I am only getting the first id and not getting the rest of the id when i alert


Here is my input code

@foreach (entrepreneurs as entrepreneur)
<form name="ent-from" id="ent-form">
    <input type="hidden" name="entrepreneur_id" id="entrepreneur_id" value="{{ $entrepreneur->id }}" readonly>
</form>
<button type="button" class="btn btn-custom" id="accept-btn">Accept</button>
@endforeach

Ajax

$('#accept-btn').on('click', function() {
    var entrepreneur_id = $('#entrepreneur_id').val();
    alert(entrepreneur_id);
});

Controller

public function handleAdmin()
{
    $entrepreneurs = Entrepreneur::paginate(5);
    return view('handleAdmin', compact('entrepreneurs'));
}
2 Answers

You cannot give ID to multiple elements. You need to use a class. Since you are giving multiple IDs it will only track the click event of the first occurrence. You need to manage it by class.

@foreach (entrepreneurs as entrepreneur)
<form name="ent-from" id="ent-form">
    <input type="hidden" name="entrepreneur_id" id="entrepreneur_id" value="{{ $entrepreneur->id }}" readonly>
</form>
<button type="button" class="btn btn-custom accept-btn" data-id="{{ $entrepreneur->id }}">Accept</button>
@endforeach

jquery

$('.accept-btn').on('click', function() {
    var entrepreneur_id = $(this).data('id');
    alert(entrepreneur_id);
});

To submit a list of itens (in this case is entrepreneur) it has to end with [] to indicate that its an array of itens. This will allow you to get all these itens in the server side when you submit it.

@foreach (entrepreneurs as entrepreneur)
<form name="ent-from" id="ent-form">
    <input type="hidden" name="entrepreneur_id[]" class="entrepreneur" value="{{ $entrepreneur->id }}" readonly>
</form>
<button type="button" class="btn btn-custom" id="accept-btn">Accept</button>
@endforeach

Change your click event by submit:

$(document).on('submit', '#ent-form', function() {
    $.ajax({ url: "/url", data: $(this).serialize() });
});
Related