Certain parts not loading on ajax requested page - javascript

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.

Related

Handling url targeted PHP page with custom jQuery loaded content

First I used include('pageName.php'); for every page I wanted to load.
Now I decided to rewrite everything and to load a page in a <div id="page_content"></div> with the jQuery function: $('#page_content').load(pageurl, {access:true});
I hope this is the best practice. Because I want to reduce load time on my web application by not refreshing the whole website with all CSS and JS files but just to refresh content when clicked on a new page.
Currently I am using the following function to load pages into the division and to pushState to history:
//Dynload pages
$("a[rel='dynload']").click(function(e) {
e.preventDefault();
var page = $(this).attr("page");
var pageurl = "pages/" + page + ".php";
$('#page_content').load(pageurl, {access:true});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',page);
}
//stop refreshing to the page given in
return false;
});
This works perfectly.
I have this button that triggers this function and gives for attribute page="index_content" . The function will load this page to the division and the state is being pushed into the history.
However. We get an url something like this: https://mywebsite.com/index_content
The problem is, when I load this specific URL into my browser I get : "Page not found" ofcourse, because it is trying to search for the index_content folder which does not exist.
Is there a way to check the url by my PHP/jQuery script and to load the correct page into the division? If not, how can I solve this for a generic case.
When I add a new page, I want to spend no- to very less time on the pageswitcher function.
In that way I can also handle non-existing pages.
Thanks in advance!

How to get the contents of a Third Party lazy loading page?

Via a Chrome extension, I'm trying to get and modify the contents of a third-party page. Everything works for the part of the content that's immediately visible on initial page load.
The problem is that this page has a lazy-load/ajax pagination. To get all of the content I have to click "view all" (ajax link) (and I believe this works essentially the same way as lazy-loading that's why I put that keyword in the title).
Upon clicking that link (on that third-party website) all content gets loaded and becomes visible to the user but when I view source there's still only the originally loaded content present in the source code. i.e. none of the freshly loaded content can be found anywhere when I view page source after the new content has been loaded. The content is visible to the end user but not visible to me when I check the source code.
Initially, I tried to overcome the problem by using setInteval and checking the page content every second but as that wasn't working I checked the source code and sure enough, none of the newly loaded content is visible in the source code. No wonder my Chrome extension can't get that content.
Another confusing thing I just realized when typing here:
When I view source code, even the initial HTML content that my Chrome extension is detecting/loading is NOT actually present in the source code! It actually sits in a JavaScript array. So, somehow, my Chrome extension is correctly getting the initial HTML content that's constructed from that JS array. But it's NOT getting the content that gets loaded after clicking the "view all" ajax link on that page (even though I'm using setInteval and checking for new content every second).
What are possible solutions for this?
I can't post the link to the page because it's the "my certificates" page on Lynda.com and I don't know of a publicly accessible website/page with the same behavior.
you should find the actual service running in network-panel, when lazy loading happens, and then follow following code
//recursively make calls and gatther responses. cb is callback to run on response, end is end page-no (end of recursion condition) , pageId is the attribute changing in every subsequent lazy-loading call.
var callIfRequiredConfigured = ({cb,end,step=1,pageURL,pageId})=>callIfRequired = ()=>{
currentCounter = currentCounter + step;
if (currentCounter > end) {
return;
}
(async(currentCounter)=>{
queueCounter++;
//modify this as needed
const r = await fetch(pageURL+currentCounter,{credentials:"same-origin"});
//queueCounter to not make more than 6 calls at once
if (queueCounter > 6) {
return;
}
var response = await r.text();
cb(response);
queueCounter--;
callIfRequired();
}
)(currentCounter);
};
var call = (config)=>{
const callIfRequired = callIfRequiredConfigured(config);
callIfRequired();
}
call({
cb: (response)=>{
//do somrthing with response
}
,
end: 50,
step: 1,
pageId: 'PageNumber=',
pageURL: `https://www.lynda.com/home/CertificateOfCompletion/GetCertificatesByFilter?Start=0&Limit=99999&SortBy=CompletionDate&SortByOrder=1&_=[my_personal_id]&PageNumber=`
});
So main effort will be to deduce the service endpoint here and how it changes in subsequest requests. I have updated the url given in comments, but see if the fetch call is successful. Also this url should also have [my_personal_id] as given in url.

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

how to refresh the browser after the page is loaded

I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.

Preloader for dynamic content

I have dynamic page which takes about 8 seconds to load searched data.
Problem is, all browsers remain on old page for those 8 secs & show dynamic page only after it
loads completely.
What I want is preloder image to be shown to the customers until second page gets load.
How can I achieve this?
Thanks
I assume you are loading the second page through AJAX. If so, you'll only be able to display the results after the asynchronous call returns.
However, nothing prevents you from making changes to the page before sending off the AJAX request. The basic structure will be:
var preload = $('<div></div>').text('I am preloading!').insertAfter('somewhere');
$.get(..., function() {
preload.remove();
// insert your real content, received from this AJAX request
});
$('<div id="busy">Loading...</div>')
.ajaxStart(function() {$(this).show();})
.ajaxStop(function() {$(this).hide();})
.appendTo('body');
That's all!
You may want to add some style to #busy tag, but this you can do with CSS.

Categories