I'm trying to fetch blogs using AJAX function in Laravel. But it is not working, neither showing any error . What I want is to display a load more
button from where more blogs will be loaded using AJAX request. Here is my front-end code:
<div class="panel-body">
{{ csrf_field() }}
<div id="post_data"></div>
</div>
And my ajax script:
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token)
{
$.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#load_more_button').remove();
$('#post_data').append(data);
}
})
}
$(document).on('click', '#load_more_button', function(){
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
});
});
Here is my route:
web.php
Route::post('/loadmore', 'LoadMoreController@load_data')->name('loadmore.load_data');
Here is the controller function:
LoadMoreController.php
class LoadMoreController extends Controller
{
public function load_more(){
function load_data(Request $request)
{
if($request->ajax())
{
if($request->id > 0)
{
$data = DB::table('blogs')
->where('blog_id', '<', $request->id)
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
else
{
$data = DB::table('blogs')
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
$output = '';
$last_id = '';
if(!$data->isEmpty())
{
foreach($data as $row)
{
$output .= '
<div class="row">
<div class="col-md-12">
<h3 class="text-info"><b>'.$row->blog_title.'</b></h3>
<p>'.$row->blog_content.'</p>
<br />
<br />
<hr />
</div>
</div>
';
$last_id = $row->id;
}
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
</div>
';
}
else
{
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
</div>
';
}
echo $output;
}
}
}
}
I'll be happy to provide any other details if needed or asked. Any suggestions/solutions will be highly appreciated.
Laravel version 8
web.php Here is route file below:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/loadmore', [App\Http\Controllers\LoadMoreController::class, 'index']);
Route::post('/loadmore/load_data', [App\Http\Controllers\LoadMoreController::class, 'load_data'])->name('loadmore.load_data');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.