Infinite Loading using a HTML Partial - javascript

Basically, I'm trying to create an infinite loading page on the product listing using a load more and firing a click event on the pagination.
My issue is that I can load the next page into the HTML but it is pulling in the whole HTML file and not just the products.
I'm trying to use a HTML partial to append the next page products into the current div.
This is my JS currently.
$(".page-next a").on("click", function (e) {
e.preventDefault();
var partial = "#Html.Partial('_ProductWithHover')";
var url = $(this).data('url');
$.ajax({url: url,method: 'GET',dataType: 'html', success: function (data) {
$('#js-infinite-scroll-page').append(partial);
}
});
});
Not sure if I should include my partial the way I have, so any feedback or advice on how to get this working would be great.
Thanks in advance!

Since this is an asynchronous behaviour you probably should change your backend api to respond with the necessary json, and construct the dom on the client side. That is way easier. Also, I don't exactly see, how do you provide information to your backend service about the current state of the infinite loading.
So infinite loading is a glorified pagination, it works like this:
You render some number of elements initially, and when you scroll enough, you trigger a request to load the next n elements, and you append them to your list. For this to work, you have to let the backend know where you stand, and after that it can return the next n elements.

Related

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

jQuery: Reload a DIV which was already loaded by AJAX (without url)?

I load a div by a simple
$('#thediv').load("theurl/param1/param2/param3");
The params differ - and I grab them from different points - depends on where the user clicks. (Different filter options..)
Now I'm searching for a simple way to reload this content with the url it was actually loaded - to avoid searching for the right filter params at this place. It is possible?
jQuery will not "save" the source of information on its own, but it is possible to specify it manually using the .data() method alongside the initial .ajax()
This means during the initial load, you can associate a URL with a div by saying something like .data("source-url","MY URL GOES HERE")
After that, you can look up that information the next time you want to reload it by using .data("source-url")
For Example:
function reloadDivs() {
// Look up all of the divs that we might want to reload
$("div.reloadable").each(function(i,el) {
// For each div, check to see if the source-url was set
// If it was set, re-run the ajax call
var $el = $(el);
if($el.data("source-url")
$el.load($el.data("source-url"));
});
}
$(function() {
// Set the initial source, change mypage.html to your actual source
$("#example-div").data("source-url","mypage.html");
$("#refreshbutton").click(reloadDivs);
});
Hope this helps!

Certain parts not loading on ajax requested page

I build this website: http://newslist.ca/
Recently, I changed it so when you chose something different from the drop down menu, the page updated immediately with the new feed. But I noticed that everything that should load based off of that new content doesn't load. Mainly: the sharing buttons, and the number of comments on each article?
What am I doing wrong, and how can I fix it?
$('.ajax').change(function() {
var url = "/?cat=" + $("select option:selected")[0].label + "&loc=" + $("select option:selected")[1].label + "&sort=" + $("select option:selected")[2].label;
console.log(url);
$.get(url, function (data) {
$('body').empty();
$('body').append(data);
})
});
The social media icons do not load when you refresh the page content entirely as they are inserted via JavaScript that is waiting for the document body to finish loading and fire an event. My thought is that your comment count method is using a similar method. Xymostech's comment above regarding using Ajax to load small bits of data into the page rather than the entire page contents is correct; you'll most likely want to load the comment counts as data with each item and leave the share tools in place (ie don't reload them) should you decide to revisit the Ajax method.

ajax div reloads with correct data, but with entire webpage within div

I have a div that contains a student's schedule, and there is a drop-down box for selecting by semester.
Once they select the semester, there is an ajax post, but when it refreshes, it displays the entire website within that div (with the appropriate schedule for that semester).
It looks like an iframe within a webpage, as seen here: http://cl.ly/Dy3b
Here is the ajax post script
<script type="text/javascript">
$(document).ready(function() {
$('#term').change(function() {
var form_data = {
term : $('#term').val(),
ajax : '1'
};
var u = $("#schedulePortletURL").attr("href");
$.ajax({
url: u,
type: 'POST',
data: form_data,
success: function(msg) {
//alert(u);
$('#view-schedule').html(msg);
}
});
return false;
});
});
</script>
If possible, could you give me some suggestions of what to investigate to correct this? Thank you
My guess is that the call to the server is returning a full HTML page, and your code then puts the full HTML page into the view-schedule div.
To resolve this, create a new HTML page that you can call that contains a html fragment - the chunk that you want to live in the view-schedule div. Then change schedulePortletURL to point to the new HTML page.
Alternately, you could get the html back (the msg) and parse it to pull out the data you are interested in, then insert the filtered data into the view-schedule div.
Does the existing website have a API at all that you can call?
Another possibility is that some kind of error checker in your server-side script is mistakenly firing and causing a redirect to some web page. That web page is then retrieved by the AJAX, then displayed in the DIV. I have had this happen before. You should check your server side script.
If you do not have full control over the webpage you are fetching the fetched page should be considered unpure and you should use iframe. Remember that with .html(blob) you will also get javascript code, flash objects etc. which can be used to compromize your users.
If you on the other hand have full control over the fetched webpage (which I assume) you should make a if-statement in your template that checks if the request is ajax-based.:
Pseudo serverside template code:
if not request.is_ajax():
import header.html
import body.html
if not request.is_ajax():
import footer.html

jQuery replace all HTML

I'm trying to replace all the HTML (including the HTML tags) with another page. What I'm trying to do is having a website acting as an app even when navigating the another page.
Here is the code :
(function($) {
Drupal.behaviors.loadingPage = {
attach: function(context,settings) {
$('a').click(function(event) {
event.preventDefault();
// Create the loading icon
// ...
$.ajax({
url: $(this).attr('href'),
success: function(data) {
$('html').replaceWith(data);
}
});
});
}
};
})(jQuery);
I've tried several things. replaceWith() causes a jQuery error in jquery.js after deleting the HTML tag, I guess it is because it can't find the parent anymore to add the replacement.
The best result I got was with document.write(data). The problem is, the javascript code on the loaded page is not executed.
Anyone got a better idea ?
A better idea? Yeah, just load the new page normally by setting window.location instead of using AJAX. Or submit a form.
Otherwise, if you want to load something to replace all of the visible content of the current page but keep the current page's script going, put all the visible content in a frame sized to fill the browser window - which, again, you wouldn't populate using AJAX.
(I like AJAX, but I don't see why you'd use it to replace a whole page.)

Categories