Laravel Ajax Pagination links refresh on second page click - javascript

I'm using Laravel 5.8 and I'm trying to make a pagination using AJAX and it's working 50% of the time. Actually, when I click on the links page at the bottoms, it renders the data perfectly, but my problem is that, the second time I press a pagination link at the bottom, it resfreshes the page. I don't want the page to reload half the time I click on pagination pages.
Here's my code for that:
ManagerController.php
public function index()
{
$users = User::paginate(30);
if (Request::ajax()) {
return Response::json(View::make('manager.usersTable', compact('users'))->render());
}
$user = User::find(Auth::user()->id);
$leagues = League::all();
$usersCount = DB::table('users')->count();
return view('manager.index', compact('user', 'leagues', 'users', 'usersCount'));
}
index.blade.php
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page === Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function() {
$('.leagueModal').on('shown.bs.modal', function (event) {
var href = $(this).find('#href_link').val();
$(this).find('#leagueModalBtn').click(function() {
window.location.href = href;
});
});
$('.pagination a').on('click', function (e) {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});
});
function getUsers(page) {
$.ajax({
url : '?page=' + page,
type: 'GET',
dataType: 'json',
}).done(function (data) {
$('.usersTable').empty().html(data);
location.hash = page;
}).fail(function () {
console.log('Users could not be loaded.');
});
}
......... Down below is where I put my data .........
<div class="row">
<h3>Utilisateurs ({{ $usersCount }})</h3>
</div>
<div class="row">
<div class="usersTable" style="width: 100%">
#include('manager.usersTable')
</div>
</div>
usersTable.blade.php
Whatever there is in this file is not really important but I got this at the end of it:
{!! $users->render() !!}
Current situation: Causes a page reload on the second time I click on a pagination link.
What I want: To not reload the page when I click on pagination links.
What I've tried: I actually followed this source code: https://gist.github.com/tobysteward/6163902
Thanks :)

You are attaching click method to .pagination a once document is ready, however if you create a new element with same class will not have same functionality. To achieve this you have to force script to check document dynamically. Please see below example.
$(document).on('click', ".pagination a", function() {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});

In laravel if you are using yajra datatable add below function
function reload_table(){
table.ajax.reload(null,false);
}
and call reload_table() instead table.draw() it will not create whole table but only reload

Related

Making a single page application with ajax and get a 404 error when the page is reloaded

Basically, I'm coding a personal website and have made a single page application with ajax so content is added to the page between the header and footer when a page in the navigation bar is clicked. I had to manually code the push state and pop state in order to get the back and forward arrows working, which they do. However, the only issue left is that when I reload the page, I get an entry not found error.
I'm very new to web dev and javascript so some of my code is a little messy. I know the reload issue has to do with the added page URL not actually existing on the server.
Here are the relevant pieces of my code:
HTML:
<nav>
<ul class='nav-bar'>
<li class='nav-item'><a id='writing'>Writing</a></li>
<li class='nav-item'><a id='editing'>Editing</a></li>
<li class='nav-item'><a id='about'>About</a></li>
<li class='nav-item'><a id='contact'>Contact</a></li>
</ul>
</nav>
Javascript
//change page on nav click
$('.nav-bar li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('id');
var file = page + '.html';
var origin = window.location.origin;
//nav color change for current page
removeActiveLinks();
$(this).parent().addClass("active");
$.ajax({
type: 'GET',
url: origin,
dataType: 'html',
success: function(response) {
$('#content').load(file);
},
error: function(error) {
console.log('There was an error', error);
}
});
window.history.pushState(file, null, '/' + page);
});
//nav for home page
$('#home').on('click', function(e) {
e.preventDefault();
removeActiveLinks();
$('#content').load('home.html')
window.history.pushState('index.html', null, '/');
});
//ensure page back functionality
window.addEventListener('popstate', function(event) {
var prevState = event.state;
$('#content').load(prevState);
removeActiveLinks();
var page_id = '#' + prevState.split('.')[0];
$(page_id).parent().addClass('active');
});
Here's what the error looks like
I would suggest something simpler, using simple load() (shorthand for ajax) and a the state of the history directly.
Not tested, but should work fine.
// Initial page load
$(document).ready(function(){
$("#content").load("home.html");
})
// Change page on nav click
$(".nav-bar li a, #home").on("click", function (e) {
e.preventDefault();
var file = this.id + ".html";
//nav color change for current page
$(".active").removeClass("active");
if(this.id != "home"){
$("#"+this.id).parent().addClass("active");
}
$("#content").load(file);
window.history.pushState(file, null, "/");
});
// Ensure page back functionality
window.addEventListener("popstate", function (event) {
var prevState = event.state;
$("#content").load(prevState);
var page_id = "#" + prevState.split(".")[0];
$(".active").removeClass("active");
if(page_id != "#home"){
$(page_id).parent().addClass("active");
}
});
But there is no /writing in the adress bar with this solution. If you insist on it, you will have to dive in more complex route settings on the server.

maintain ajax pagination upon clicking back button in Laravel 5.3 application

I'am making use of laravel pagination($data->links()) for ajax pagination using below code.
$(document).on("click", '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
loadArts(url);
});
function loadArts(url) {
$.ajax({
url : url
}).done(function (data) {
$(".image-masonry").html(data);
jsIntializations()
}).fail(function () {
alert('Articles could not be loaded.');
});
}
it's working fine, but upon clicking back button from an inner page, browser returning back to page1.
Here is the controller function
public function index(Request $request)
{
$arts = Art::with('artist')->orderBy('id','ASC')->paginate(10);
if($request->ajax()){
return view('art::art.list', compact('arts');
}
return view('art::art.index', compact('arts');
}
.image-masonary is the class in index.blade.php to which contents of list.blade.php is being loaded upon pagination.
This is the url : http://localhost:8000/admin/arts
I tried this method , history.pushState({ path: url }, '', url);
then back button is taking ajax route, but getting only broken view.
You may refer to the answer below
https://blog.pisyek.com/browsers-back-button-issue-after-logout-laravel-5
https://laracasts.com/discuss/channels/requests/back-button-browser?page=1

Prevent a link from loading the clicked link in the modal window

I have a list of links which when clicked should open a modal window with some information. I am using e.preventDefault(); to prevent the default action of the browser and then add my own custom code to load my own data in the modal. The content loads just fine but after a few seconds the whole website whose link I clicked get loaded inside the modal.
It only happens with links from a specific website.
The links from that website should be the first one that I click. Clicking on other links first resolves this issue.
Here is my code:
$('a.modal-link').on('click', openModal);
function openModal(evt) {
evt.preventDefault();
var link = $(this).attr("href");
var text = $(this).text();
safeModal(link, text);
};
function safeModal(linkUrl, linkText) {
var link = linkUrl;
var page = window.location.href.split('?')[0];
var text = linkText;
var ajaxURL = "http://example.com/script.php";
$.ajax({
type: "POST"
, url: ajaxURL
, data: {
link: link
, page: page
}
, success: function (markup) {
$(".feed-modal .modal-body").html(markup);
}
})
};
I can also provide the link to the actual website, so you can see the issue yourself (I may not have explained it properly).
UPDATE: I am adding the link. Try clicking on the first headline and you will see the issue. After that, reload the webpage and then click on the sixth link. Now, close the modal and click on the first link again. Everything should work perfectly this time.
UPDATE: The syntax error doesn't exist. I made it in the question by mistake. :)
This code has a syntax error (delete })):
success: function (markup) {
$(".feed-modal .modal-body").html(markup);
}) //delete this
}
The whole function should be:
function safeModal(linkUrl, linkText) {
var link = linkUrl;
var page = window.location.href.split('?')[0];
var text = linkText;
var ajaxURL = "http://example.com/script.php";
$.ajax({
type: "POST"
, url: ajaxURL
, data: {
link: link
, page: page
}
, success: function (markup) {
$(".feed-modal .modal-body").html(markup);
//}) without this
}
})
};
Working DEMO

Load AJAX content in modal and change URL

My current setup is on click a modal popups with data from the ajax action which has been passed an id, I want the URL to change on click.
But I also want it so that if you directly accessed the URL it would load say index with the modal preloaded.
Very much like https://www.myunidays.com/perks/view/shoeaholics/online it loads the URL with the content in a model then if you click/close the modal the URL changes to the index page.
I have seen related questions about changing URL on click but couldn't find anything to do with accessing URL directly (is their a rule I can add to my .htaccess).
(Any code/direction is appreciated)
Create a partial view (so that layout isnt rendered twice) and add the action to controller
public function actionViewmodal($id)
{
return $this->renderPartial('_view', array('model' => $this->findModel($id)));
}
Then within my index I did the following
$(document).ready(function() {
$('a').click(function() {
pageurl = $(this).attr('href');
var Id = jQuery(this).attr('id');
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : 'http://localhost:8888/directory/viewmodal?id='+Id,
success: function(response) {
if(response) {
$('.modal_some_wrapper').html(response);
$('#modal_'+Id).modal('show');
$(document).on('hidden.bs.modal', modal_id, function (event) {
$(this).remove();
});
} else {
alert('Error');
}
}
});
//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
});
Could someone example how myunidays website works with modal and URL change?

jQuery: Simple menu

I'm trying to learn jQuery by implementing a simple menu. I've got <div> elements that act as buttons and have links in them. I'm trying to add onclick events to the divs that navigate the browser to the link's address in the div. This is basically my pseudo-code. What would the real code be? How can I improve this? Any feedback appreciated!
// Iterate over each menu button
$('.masterHeaderMenuButton').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var url = $('a', this).attr('href');
this.click(function () {
window.location.href = url;
});
// If the user is on the page for the current button, hilight it
if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});
Try this untested example:
$('.masterHeaderMenuButton a').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});
// If the user is on the page for the current button, highlight it
if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});
I don't actually use jQuery for such a simplistic task, especially if it involves page redirection. So unless you're looking to do some AJAX-style page loading, stick with standard HTML.
For that task, I use this sweet combo:
$('#nav_links li').live('click', function() {
var ajax_link = $(this).attr('rel');
loadLink(ajax_link);
});
function loadLink(link){
$('#content_window').css('position','relative');
$('#content_window').animate({
'left': '20px',
'opacity': '0'
}, 500, "swing", function() {
$.ajax({
url: '../sections/' + link,
dataType: 'html',
success: function(html) {
$('#content_window').html(html);
}
});
});
}
Awesome, right?
Here's the HTML:
<ul id="nav_links">
<li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
<li rel="features.html"><span class="purple">|</span>features<br></li>
<li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
<li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>
Have a fun.

Categories