The following code works fine. When a user clicks on an element, an AJAX request is made, which will return the query result. The results are being displayed in a view. I read many articles where everyone is doing HTML code in controller when getting data with AJAX and show in view as same I did. Any good suggestions to avoid HTML code in controller make controller view and script separate.
Controller:
public function ajax(Request $request){
// $data = $request->all();
$data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();
foreach ($data['products'] as $product){
echo $product->name;
}
// dd($data);
// if($request->ajax()){
// return "AJAX";
// }
// return "HTTP";
// $data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();
// return $data;
}
Script
<script type="text/javascript">
// $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
$(document).ready(function(){
// Load more data
$('.load-more').click(function(){
var row = Number($('#row').val());
var allcount = Number($('#all').val());
var rowperpage = 3;
// row = row + rowperpage;
row = row + 3;
if(row <= allcount){
$("#row").val(row);
$.ajax({
url: "{{ route('ajax') }}",
type: 'post',
datatype: 'JSON',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data: {row:row},
// error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('hi');
// }
success: function(response){
// Setting little delay while displaying new content
setTimeout(function() {
// appending posts after last post with class="post"
$(".post:last").after(response).show().fadeIn("slow");
var rowno = row + 3;
// checking row value is greater than allcount or not
if(rowno > allcount){
// Change the text and background
$('.load-more').text("show less");
$('.load-more').css("background","darkorchid");
}else{
$(".load-more").text("Load more");
}
}, 2000);
}
});
}else{
$('.load-more').text("Loading...");
// Setting little delay while removing contents
setTimeout(function() {
// When row is greater than allcount then remove all class='post' element after 3 element
$('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");
// Reset the value of row
$("#row").val(0);
// Change the text and background
$('.load-more').text("Load more");
$('.load-more').css("background","#15a9ce");
}, 2000);
}
});
});
</script>
view
@foreach($leedManufacturers as $leedsManufacturer)
{{-- @foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['name'], 300)}}
<input type="checkbox">
<span class="checkmark"></span>
</label>
</div>
{{-- for load more script --}}
{{-- <input type="hidden" id="row" value="0"> --}}
{{-- <input type="hidden" id="all" value="{{$total_manufacturers}}"> --}}
@endforeach