Good Evening.
I am working on home based project and new learner to the Laravel and coding.
Here i am trying to get the Card header value in ajax to pass controller and get data from the same.
Card header showing the month name which is in loop.
here is the code
@foreach ($totalmilkselldataforyeartotable as $item)
<div class="col-md-4 col-sm-6 col-lg-2">
<div class="card border-success " style="width: 12rem;">
<div class="card-header">
<span id="monthnameforcard"> <strong>{{ $item['monthname'] }}</strong> </span>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Total Milk - <strong>{{ $item['totalmilk'] }}</strong></li>
</ul>
<button type="button" class="btn btn-link">
<span id="getmonthmilkdetails" class='glyphicon glyphicon'> More <i class="fas fa-arrow-circle-right"></i> </span>
</button>
</div>
</div>
@endforeach
code for Ajax.
$(document).on('click', '#getmonthmilkdetails', function() {
var getmonthnameforajax = document.getElementById('monthnameforcard').value;
alert(getmonthnameforajax);
$.ajax({
type: 'post',
url: '/getmonthmilkdetails',
data: {
'_token' : $('input[name=_token]').val(),
'monthname' : getmonthnameforajax,
},
success: function(data) {
}
});
});
alert box showing "Undefined "
Thanks for help
>Solution :
I suggest you use class instead of id and use closest to get the parent element that has card class then use querySelector to get the element has monthnameforcard class
@foreach ($totalmilkselldataforyeartotable as $item)
<div class="col-md-4 col-sm-6 col-lg-2">
<div class="card border-success " style="width: 12rem;">
<div class="card-header">
<span class="monthnameforcard"> <strong>{{ $item['monthname'] }}</strong> </span>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Total Milk - <strong>{{ $item['totalmilk'] }}</strong></li>
</ul>
<button type="button" class="btn btn-link">
<span class='glyphicon glyphicon getmonthmilkdetails'> More <i class="fas fa-arrow-circle-right"></i> </span>
</button>
</div>
</div>
@endforeach
$(document).on('click', '#getmonthmilkdetails', function(E) {
var getmonthnameforajax = e.currentTarget.cloest('.card').querySelector('. monthnameforcard').textContent;
alert(getmonthnameforajax);
$.ajax({
type: 'post',
url: '/getmonthmilkdetails',
data: {
'_token' : $('input[name=_token]').val(),
'monthname' : getmonthnameforajax,
},
success: function(data) {
}
});
});