Truly Refresh/Reload a jQuery mobile page div - javascript

I'm currently working with a file that contains several jQM page divs (single page approach).
I have a refresh button in the header of these pages that I'm trying to get to refresh individual page divs based on "getActivePage". The reason for this interactivity is there is a running list of items that users will be needing to refresh to see new content coming in to listview(s).
I've had various visual refreshes altering the following function, but none seem to totally refresh the DOM or the contents of a desired pagecontainer or jQM page div. With the following code, I'm able to see a visual transition and I arrive at the desired/same jQM page div that I'm trying to refresh. The problem is, the contents aren't really being reloaded it seems. (I have a way in the test environment of changing the listviews to test the refreshes and I'm not seeing those changes take effect) I'm wondering if I'm not passing in "id_urlNav" properly or if this is even possible with .pagecontainer("change"...).
When all was lost, I ended up inserting window.location.reload();, but this seems to be bad form for pagecontainer manipulation. If anyone has any idea why this isn't working, please let me know. Thanks in advance for reviewing!
// script to reload/refresh jQM pages
// scoped to internal page hashes vs. overall window
// "change" is used vs. "load" for internal reloads vs. AJAX content
function refreshPages() {
// the camel casing on the first part of the pageContainer object below
// is important
var id_url = $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
var id_urlNav = "#" + id_url;
console.log("id_urlNav" + " =" + " " + id_urlNav );
// window.location.reload();
// keeping the below in case 1.5 finally arives with proven solution
$.mobile.pageContainer.pagecontainer( "change", id_urlNav,
{
allowSamePageTransition : true,
showLoadMsg : true,
// reloadPage reloads entire jQM set of pages, forgetting the getActivePage
// reloadPage is deprecated
// reload "reloads" the getActivePage, but doesn't show new content
reload : true,
transition : 'fade',
changeHash : 'true'
}
);
}
// /refresh code
I read some on the jQuery forums about there being a bug related to reload: vs. the now deprecated reloadPage:, but I don't know if that is some of the cause of the malfunction or not.

Related

Interactive grid in modal dialog cannot be selected anymore via jQuery

Background Information:
Our situation
At work we have created multiple apps and a few of them make use of an interactive grid inside of a modal dialog page. Last week we upgraded from Oracle APEX 19.1 to Oracle APEX 21.1 .
The problem described below didn't exist in version 19.1.
(If important: We have to support Google Chrome on Windows)
How to navigate to the IG
In all our cases the interactive grid can be reached by:
nagivating to page x
open modal dialog y
from modal dialog y open modal dialog z (via a branch after page processing)
=> the interactive grid can be found in modal dialog z
Aim and preparations
We only want to give the users access to a few interactive grid functionalities.
For this reason we gave each IG a static id.
What still works
The modal dialog opens and the interactive grid is displayed normally.
Our Problem
Up until the upgrade the following snippet removed some functionality of the respective IG:
$(window).on("load", function() {
var actions = apex.region("example_ig_id").widget().interactiveGrid("getActions");
actions.remove("selection-copy-down");
actions.remove("selection-fill");
actions.remove("selection-clear");
actions.remove("single-row-view");
actions.remove("selection-copy");
});
But since upgrading to version 21.1 apex.region("example_ig_id") returns null. The dom element also can't be found via $("#example_ig_id").
What we found out and tried
In the google chrome developer tools the div with id example_ig_id is visible under elements.
After loading the page, then clicking into the class attribute of the div (via developer tools) to edit it (no need to realy edit anything) and canceling it, apex.region("example_ig_id") isn't returning null anymore. That also works if I edit its direct or indirect parent elements (also tested with the iframe of the modal dialog containing the IG).
Since finding that out i tried to work around the problem with forcing a refresh or a reflow.
I tested multiple of the answers given here: Force DOM redraw/refresh on Chrome/Mac
The tests I tried (in the inline console) all didn't solve my problem:
$("iframe").each(function(){$(this).addClass("testClass"); $(this).removeClass("testClass");});
and:
$("iframe").each(function(){$(this).hide(); $(this).show(0);});
and:
$("iframe").each(function () {
$(this).css("opacity", .99);
setTimeout(function () {
$(this).css("opacity", 1);
}, 20);
});
I used the iframe of the modal dialog itself since it is selectable from the start.
I am not sure if I made a mistake but help would be much appreciated.
At this point I got help and the problem is solved.
Instead of defining this'
$(window).on("load", function() {
var actions = apex.region("example_ig_id").widget().interactiveGrid("getActions");
actions.remove("selection-copy-down");
actions.remove("selection-fill");
actions.remove("selection-clear");
actions.remove("single-row-view");
actions.remove("selection-copy");
});
inside the page under
Function and Global Variable Declaration
pasting just the function content
var actions = apex.region("P7_SAVED_JOBS_IG").widget().interactiveGrid("getActions");
actions.remove("selection-copy-down");
actions.remove("selection-fill");
actions.remove("selection-clear");
actions.remove("single-row-view");
actions.remove("selection-copy");
into the page under
Execute when Page Loads
did the trick.
I don't know if the execution time of the event handler was too early or if it had something to do with the iframe and its context.

How to keep elements non-refreshed

The main goal is to keep non-refreshed the logotext <div class="small-7 medium-4 columns logo"> and the menu <nav class="pagedMenu" role="navigation">,without clipping on page refresh or while the content is loading from a page to another. Also, the menu state should be preserved from a page to another.
I've found here a possible solution that could solve the problem (you could use ajax to fetch the updated content and use jQuery to put the new content on the page and avoid the refresh entirely. Doing it that way, the existing data in the page would remain untouched. said #jfriend00)
So, I have tried to use an Ajax plugin (called AWS). In the AWS option page, I (suppose) that I've done the right thing pointing wrapper as Ajax container ID and also pagedMenu as Menu container class, Transition Effect Enabled, No ajax container IDs blank, no loader selected, having already a pulse loader implemented in the theme.
At this point, all I got it's a menu / side-menu (shiftnav) / pulse dot loader / content loading malfunction, generated perhaps by the wrong defined Ajax container id and/or menu container class(?) OR by a conflict with an existing JS / jQuery code, not so sure.
Also in Chrome console there is an error:
Uncaught SyntaxError: Unexpected token ;
(anonymous function) # ajaxify.js?ver=4.3.1:175
n.extend.each # jquery-2.1.4.min.js?ver=2.1.4:2
n.fn.n.each # jquery-2.1.4.min.js?ver=2.1.4:2
$.bind.$.ajax.success # ajaxify.js?ver=4.3.1:169
n.Callbacks.j # jquery-2.1.4.min.js?ver=2.1.4:2
n.Callbacks.k.fireWith # jquery-2.1.4.min.js?ver=2.1.4:2
x # jquery-2.1.4.min.js?ver=2.1.4:4
n.ajaxTransport.k.cors.a.crossDomain.send.b # jquery-2.1.4.min.js?ver=2.1.4:4
Everything is getting back to normal on page refresh but doesn't help at all, being useless.
I also have to mention that for the menu I've tried to keep the state using jQuery-Storage-API and storage=jQuery.sessionStorage; as you can see in mynewmenu.js file but that will not solve the non-refreshing elements problem.
The menu jsfiddle only, if this helps to have the whole picture, here thanks to #Diego Betto.
You can use this live link as example; there is a similar situation with the above described - Ajax implementation right(?) - and regarding the appearance, menu is kept non-refreshed from one page to another; if you browse Books, Works etc, menu sections you'll see; if there is a model that could be implemented here, I'll be glad to find it.
LE: meanwhile, I've tried another ajaxify solution made by #arvgta - special thanks - without success yet but as far as I've found from the Author, the defined elements should be div's with id's not classes. So, I'll try to find a way to modify somehow the code in order to have id instead on classes.
Also, I'll try to transform and implement in ajaxify.min.js file, the page-container element; jQuery('#page-container').ajaxify(); I'll come back with news.
LE2: I've tried to implement the solution using id's instead of classes but still, the pages are not loading correctly.
At this point we have ajax.min.js file updated with these lines:
(function($){
jQuery(document).ready(function(){
jQuery('#page-container').ajaxify({requestDelay:400,forms:false});
});
})(jQuery);
Also, I've modified the theme file to have id=page-container instead if class=page-container.
In these conditions, on menu click, the links are changed (like it should), menu/ logotext elements seems to working almost fine (sometimes get skippy changing position), but the content is not loading correctly in all cases; Same here, everything is getting back to normal on manual page refresh (f5), but doesn't help.
LE3: It looks like the conflict is (at least) between Revolution Slider plugin and Ajaxify.
errormessage="Revolution Slider Error: You have some jquery.js library include that comes after the revolution files js include." ;="" +=" This includes make eliminates the revolution slider libraries, and make it not work." "<="" span="">"
Site live link here. Any thoughts / alternative in this area? (not interested in using other different platforms, different WordPress themes, etc. just a workaround in this existing situation)
LE4: As far as I can see, there are many users that voted up the Jake Bown answer that could be indeed a solution; but I can't find the reason that didn't work correctly implemented into my theme (without errors) live link here The elements logotext / menu are still fading on refresh, are not kept non-refreshed. Any thoughts #Jake Bown / anyone?
LE final.
Buzinas delivered the closest answer for my needs, taking in consideration my site environment (plugins installed, etc).
From what you said I think I might have found the solution you're looking for - you want to load content dynamically whilst keeping the logo and navigation untouched? If so, this might be what you're looking for.
In the example, the pages are loaded in from a div within the page but could be used to load another URL or file:
$('.viewport ul li a').on('click', function(e) {
e.preventDefault();
var link = this.hash.substring(1, this.hash.length);
if($('.'+link).length) {
$('.viewport span.body').html($('.'+link).html());
}
});
TL;DR
I've created a plunker for you, take a look, and play with it as long as you can. You'll learn a lot from it!
I think you're trying too many things here, but didn't try the simplest:
The main goal is to keep non-refreshed the logotext and the menu ,without clipping on page refresh or while the content is loading from a page to another. Also the menu state should be preserved from a page to another.
If you want to do that, there are a few steps:
Create a 'master' page, that we're going to call index.html from now on.
So, our index must have the static part of our page, e.g menu, logo, footer etc.
Then, our 'subpages' must be cut down (no html, head, body, script, style tags, only the content that should be showed into our master page).
That done, now we must change our links to use AJAX instead of doing full refresh:
/* we add a 'click' event handler to our menu */
document.getElementById('menu-menu-2').addEventListener('click', function(e) {
var el = e.target;
/* then, we see if the element that was clicked is a anchor */
if (el.tagName === 'A') {
/* we prevent the default functionality of the anchor (i.e redirect to the page) */
e.preventDefault();
/* we show our spinner, so the user can see that something is loading */
spinner.classList.remove('hidden');
/* and we call our AJAX function, passing a function as the callback */
ajax(el.href, function(xhr) {
/* we get our main div, and we replace its HTML to the response that came
from the AJAX request */
document.getElementById('main').innerHTML = xhr.responseText;
/* since the request was finished, we hide our spinner again */
spinner.classList.add('hidden');
});
}
});
Ok, now our pages are already working via AJAX, and not reloading our static content.
But now, we see that we have some issues. For example, if someone tries to open one of our pages directly via URL, he'll see unstyled page, without the menu/logo etc. So, what should we do?
We have a few more steps now:
Simulate that our links are effectively transfering between pages using the History API:
/* inside our ajax callback, we save the fake-redirect we made into the pushState */
ajax(el.href, function(xhr) {
document.getElementById('main').innerHTML = xhr.responseText;
/* save the new html, so when the user uses the back button, we can load it again */
history.pushState({
html: main.innerHTML,
title: el.textContent + '| neuegrid'
}, '', el.href);
/* (...) */
});
/* and outside it, we add a 'popstate' event handler */
window.addEventListener('popstate', function(e) {
/* so, if we've saved the state before, we can restore it now */
if (e.state) {
document.getElementById('main').innerHTML = e.state.html;
document.title = e.state.title;
}
});
And we need that when the user enters directly to another page, e.g about-us, we redirect him to the index.html, and then load the about-us page from there.
So we create a redirect.js file, and we reference it in all of our
subpages:
/* save the page that the user tried to load into the sessionStorage */
sessionStorage.setItem('page', location.pathname);
/* and them, we redirect him to our main page */
location.replace('/');
And then, in our index.html page, we see if there is any page in the sessionStorage, and we load it, if there is, otherwise we load our home page.
var page = sessionStorage.getItem('page') || 'home';
/* we look into the menu items, and find which has an href attribute
ending with the page's URL we wanna load */
document.querySelector('#menu-menu-2 > li > a[href$="' + page + '"').click();
And that's it, we're done now. Take a look at the plunker I've been making to you.
And play with it as long as you can, so you'll learn a lot from it.
I hope I could help you! :)
Note: Just for reference, this is our ajax function:
function ajax(url, callback, method, params) {
if (!method) method = 'GET';
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (callback) xhr.addEventListener('load', function() {
callback.call(this, xhr);
});
if (params) {
params = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
xhr.send(params);
} else {
xhr.send();
}
}
GOING AJAXED WITH WORDPRESS
demo: http://so.devilmaycode.it/how-to-keep-elements-non-refreshed/
follow these simple steps (let's take as example theme "twentyfifteen" on the WP templates folder):
edit single.php, page.php, index.php and all other pages having get_header() and get_footer() functions and replace it respectively with below code:
NOTE: this is important because if someone (ex: search-engine) reach your pages directly from the link, it is still fully available and 100% working. (useful for SEO)
<?php
//get_header()
if(!isset($_REQUEST['ajax'])){
get_header();
}
?>
<!-- other code --->
<?php
//get_footer()
if(!isset($_REQUEST['ajax'])){
get_footer();
}
?>
open the header.php add the below code inside the <head> section at the very end
<script>
!(function($) {
$(function() {
$('.menu-item a, .widget-area a, .page_item a').on('click', function(e) {
e.preventDefault();
var href = this.href;
var query = href ? (href + (!/\?/g.test(href) ? '?' : '&') + 'ajax=1') : window.location;
/* IMPLEMENT SOME LOGIG HERE BEFORE PAGE LOAD */
/* ex: kill instance of running plugins */
$('#content').hide().empty().load(query, function() {
/* IMPLEMENT SOME LOGIG HERE AFTER PAGE IS LOADED */
/* ex: refresh or run a new plugin instance for this page */
jQuery(this).show();
});
});
});
})(jQuery);
</script>
in the header.php file put the code below at the end of the file, 90% of times you need it under the navigation. In this case we already have this on the "twentyfifteen" theme.
NB: most probably you have the opening tag <div id="content" class="site-content"> inside the header.php file and the closing tag </div> on the footer.php file, this doesn't matter, you can leave it as is.
<div id="content"></div>
NOTE: consider this a proof of concept; it may work as is, but you still need to tailor it to suit your needs; you may need to:
Add a menu (in case it is not already set) by going under Appeareace > Menus > [check Primary Menu] > Save Menu in order to activate the menu. it's tested and working.
You may want to add some other class to the jQuery function like .widget-area a in order to ajax also widget links.
if you are using 3d party plugins you may need to ensure that all dependencies of each plugin are loaded also on the main page from where you want everything is displayed without refreshing content.
you may need to check and kill those 3d party plugin before a new page load and run or refresh plugin needed in the loaded page.

How to change URL path when paging using ajax + jQuery

I am using ajax post requests for doing paging on a feed in my site. When getting the post request data I am reforming the page by clearing previous data and rendering the new data that came from the request. I want to be able to change the URL as well so saving the new page link will get the user to the current page.
Example:
User on page example.com/feed - seeing content of page #1
User clicking to get to page #2 -> ajax post is send and data on the page is changed using js (no refresh)
URL is still example.com/feed but the content is of example.com/feed?page=2
How can I set the URL to point to the new page without triggering a refresh (no redirect) ?
I am using Nodejs + express.
I understand you are aiming at a single page application.
While keeping the url is nice, note you might want distinct urls for directly accessing different parts of your application. Still, you can load content with AJAX and keep a smooth application. The way to go is using the hash part of the location.
The Sammy.js framework gives you a nice base to build upon, you can try it out.
You can use history pushstate but some browsers does not support.
history.pushState({id: 'SOME ID'}, '', 'myurl.html');
And don't forget about window.onpopstate, it pops if user clicks back button.
Redirect the user to an anchor point.
Page 2
And in your document.ready:
if (window.location.hash.length > 1){
var pageNumber = window.location.hash.substring(1);
loadPage(parseInt(pageNumber));
} else{
loadPage(0);
}
I don't believe it is possible to change the query part of the URL without triggering a refresh (probably due to security issues). However you may change the anchor and use an event listener to detect when the anchor is being changed.
//Listener
$(window).on('hashchange', function() {
if(loaction.hash.length > 1) {
//The anchor has been changed.
loadPageWithAjax("example.com/feed.php?page=" + location.hash.substring(1));
} else {
//Load standard page
...
}
});
Change the anchor to load new feed
Page 2
Remember to not use an anchor that is used as an id, since this makes the browser scroll to that element.

Anchor click even not firing after PJAX page load

I am having a pretty strange problem with a website I am messing around with, and I can't wrap my head around what may be going wrong. I am using PJAX on the site, and the have a div in my body with the id of #page-contents.
The code I am using to setup PJAX is as follows...
<script type="text/javascript">
$(function(){
$(document).pjax('a', '#page-contents', {
fragment: '#page-contents',
timeout: 2000
});
});
</script>
I know that the setup is correct because I edited the PJAX file to fire an alert whenever it swapped out the content of my #page-contents div, and I do see that alert when I would expect to (i.e., on link clicks).
I have a navbar along the top (a bootstrap navbar) and I was initially having trouble keeping track of which navbar item would be marked as active. I have solved this problem using the following javascript code.
<script type="text/javascript">
$("a").click(function() {
$(".navbar-nav li").removeClass("active");
var nextPage = $(this).attr("href");
nextPage = nextPage.substring(nextPage.indexOf(window.location.hostname) + window.location.hostname.length);
switch(true) {
case nextPage == "/about":
$("#about-nav").addClass("active");
break;
case nextPage == "/contact":
$("#contact-nav").addClass("active");
break;
case nextPage == "/resume":
$("#resume-nav").addClass("active");
break;
case nextPage.indexOf("/projects") != -1:
$("#projects-nav").addClass("active");
break;
default:
break;
}
});
</script>
This works fine for all links I have in my navbar, but I have found that any links I have inside my #page-contents div will not trigger my above script. I know that PJAX is still working as the page changes and the alert I inserted displays.
A few things I have found in my own testing:
I have also found that if I directly load an address that contains a non-navbar link and then click that link, it will work. But coming back to that page via a pjax reload and then clicking the link will not fire my event.
Adding a test class to one of my anchors and then associating some event with that class has the same problems.
Does anybody know why my script would not be getting executing? Or maybe I am just missing something obvious.
Thank you in advance!
P.S.: The website in question is my personal site I am working on, the link is http://rosshays.me, the page I first noticed this on was my about page. (The site is a work in progress as you'll clearly see.) As mentioned about, going to the about page directly and clicking the link will work, but if you navigate to the about page and then try to click the link in the page, it will not work.
Ross-
I had a similar issue and I know how to solve this; this script is not binding to the new elements because it is not being re-ran on the new elements once they are loaded.
Please put your function in an external .js file. Once complete, you can add this script to your header:
$(document).on('pjax:complete', function() {
$.ajaxSetup({ cache: true});
$.getScript("YOUR SCRIPT FILE PATH HERE', true);?>");
});
You will have to add more $.getScript calls for any other javascript/jQuery that is needed in order to enable the events you want to take place. (Example: you may need to reload jQuery)
This will re-apply the jquery and javascript to the new elements that are loaded via PJAX.
*One thing to note: If you are using twitter bootstrap, do not re-call the bootstrap script with $.getScript as it will cancel itself out on every other re-load.

Changing the 'src' attribute of an image using javascript

I'm using javascript, so that when a refresh button is clicked it begins to spin around until the refresh is completed. This is my function:
function RefreshHome() {
// Refreshes the home page via the image link.
// Make the refresh link animate.
var refresh = document.getElementById("refresh_button");
refresh.src = "images/refresh_animated.gif";
// Refresh the page.
window.location = "home.aspx";
return false;
}
This worked perfectly for a while then, as far as I can see, inexplicably stopped working! When the refresh button is clicked on now, the image just disappears.
Does anybody know why this might happen?
Just want to mention that this would be much easier in jQuery. You wouldn't need to worry so much about maintaining browser compatibility etc. either. As your project grows your code may become unwieldily, so even if you don't decide to use jQuery you should find a suitable framework for your needs.
var refresh = $("#refresh_button");
refresh.attr("src", "images/refresh_animated.gif");
Also be aware that an image that has no src shows up with a placeholder X on most browsers, and you can hide it with display:none; or using the refresh.hide() and refresh.show() methods in jQuery as needed.

Categories

Resources