Contents of reports getting overwritten . Need to refresh parent page? - javascript

Please find the summary of my query:-
Lets say I start off at my homepage :- https://example.com//homepage
At the homepage I have links to certain documents .Once I click on one of the links it takes me to a page where I am asked to fill information and I can finally submit it.
I fill the information ,click on submit it takes me to final signature page where it asks me to enter my credentials so that it can post a timestamp saying that I have authored this document at this particular time.
Now I close this window and return to the homepage and click on another document link ,WITHOUT REFRESHING THE HOMEPAGE and follow the same steps. For some some odd reason when I complete this document I see that details mentioned in the first report have been leaked\merged\overwritten into this document.BIZZARE!!
So I did a bit of research(soul searching if you may say) and I found the reason could be because the session is still having the old data from the old document ?Basically what I tried was when I manually refreshed the homepage ,this issue didn't occur. So what I am trying to do now is ,every time I SIGN off the document, i.e reach the final signature page and click no 'SUBMIT' button , I want the homepage ,viz https://example.com/homepage to refresh.
Below is the snippet of JSCRIPT that is being called when I click on 'SUBMIT' button on the signature page:-(this is basically the onclick function for that 'SUBMIT' HTML function )
function completeForm(aForm)
{
var foundError = false;
if(validateRequiredInput(aForm.loginID) &
validateRequiredInput(aForm.password) )
{
document.getElementById("submitBtn").disabled = true;
// Modified to get the newWindow request Parameter by Nidhi Prakash Srivastava for clinSIGHT release 2.0.6
var newWindow = "";
if(aForm.getNewWindow != null)
{
newWindow=aForm.getNewWindow.value;
}
// Modified to get the newEPCWindow request Parameter by Nidhi Prakash Srivastava for clinSIGHT release 2.0.10
var newEPCWindow = "";
var newQCWindow = "";
if(aForm.getNewEPCWindow != null && aForm.action.indexOf("?") < 0)
{
newEPCWindow=aForm.getNewEPCWindow.value;
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow+"&newEPCWindow="+newEPCWindow;
}else if(aForm.getNewQCWindow != null && aForm.action.indexOf("?") < 0){
newQCWindow=aForm.getNewQCWindow.value;
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow+"&newQCWindow="+newQCWindow;
}else if(aForm.action.indexOf("?") < 0)
{
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow;
}
onsubmitFormHandler();
aForm.submit();
}
How do I go about achieveing the refresh of the homepage from here? Is this even the right approach ? Any suggestions on the same ?

Related

Why isn't my if statement executing correctly even though condition has been met?

This is an InDesign script to convert indd files into jpgs and then export and rename them into a folder on my desktop. It all works fine, but there is one part that I'm trying to do, which is only export the pages that do not have the Master Page "H-Advertising" applied. I've written an if statement that checks what master page has been applied to the current page of the current document and should ostensibly only export that page if it hasn't had "H-Advertising" applied as a master page. I know that the loop works if I add a different condition (such as if (3!=4)) and it is also able to alert the master page of each page, but it just seems to go ahead and add the page to the array of pages I want to export no matter what.
Main();
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if (app.documents.length > 0) {
app.jpegExportPreferences.exportingSpread = false;
//makes sure there is a book open
if (app.books.length != 1)
alert("This only works when you have one (1) book open and the first file in that book open");
else
//loop through the book's stories
for (b = 0; b < app.books[0].bookContents.length; b++) {
// initialize pages variable
var pages = [];
// loop through the pages in the active document
for (i = 0; i < app.activeDocument.pages.length; i++) {
// initialize variable holding document name, and then rename as follows
var myDocumentName = app.books[0].bookContents[b].fullName;
c = app.open(app.books[0].bookContents[b].fullName);
myDocumentName = myDocumentName.name.replace("indd", "jpg");
myDocumentName = myDocumentName.replace("WN16", "WN16_");
// get value of the current page's applied master
if (app.activeDocument.pages[i].appliedMaster != null) {
var appliedMaster = app.activeDocument.pages[i].appliedMaster.name;
}
// if it's not an advertising page, get the page number and add it to an array containing page numbers to export
if (appliedMaster !== "H-ADVERTISING" && appliedMaster!= "[None]" && appliedMaster!= null) {
alert(appliedMaster);
pages.push(app.activeDocument.pages[i].name);
printpages = pages.join(",");
// set the pageString of pages to export as jpegs
app.jpegExportPreferences.pageString = printpages;
// export all the pages using the export page range page string
c.exportFile(ExportFormat.JPG, File(Folder.desktop + "/EDIT_Jpgs/" + myDocumentName));
}
}
};
Note: Property 'pageString" is valid when JPEG export range is not all. So - just to be sure - you may need to set app.jpegExportPreferences.jpegExportRange to 'ExportRangeOrAllPages.EXPORT_RANGE'
Note2: Consider that a book could be opened without opened docs OR an activeDocument could be from outside of app.books[0] ==> in this case your loop for (i = 0; i < app.activeDocument.pages.length; i++) possibly lead to wrong values, cause target doc is opened... inside this loop.
Jarek
Okay, the script is working now, after I updated to InDesign 2017. So, not really an answer, other than there must have been a bug in InDesign. The only thing I did tweak in the code was to add this
if (app.activeDocument.pages[i].appliedMaster !== null && app.activeDocument.pages[i].appliedMaster!== "H-ADVERTISING" && app.activeDocument.pages[i].appliedMaster!==null) {
appliedMaster = app.activeDocument.pages[i].appliedMaster.name;
}
earlier in the code which checked the actual value of the master page, instead of checking a variable that was assigned the value of the master page. This seemed to be the trick to checking to filter for any pages that had no master page applied (null or "[None]")

Using $location for only part of a page breaks back button

I want to use $location to navigate a self-contained comments section on a normal statically loaded page, but it seems to break the back back button.
The problem comes when I've navigated to a few pages using $location, then click on an external link. It goes to that link, but when I hit back, it changes the URL to the last one but doesn't actually change the page (i.e. it stays on the external page). If I then keep on clicking back, it changes the URL (so the url history is fine), but it doesn't actually load up the page from that url until I get to the first one that I've visited (if that makes sense...). So, for example:
So, navigating the app:
www.example.com - loads up my page with the comments
www.example.com?page=2 - uses $location and loads the new comments correctly
www.example.com?page=3 - uses $location and loads the new comments correctly
www.externalexamplepage.com - navigates correctly to the page.
back - changes the address to www.example.com?page=3 but stays on www.externalexamplepage.com
back - changes the address to www.example.com?page=2 but stays on www.externalexamplepage.com
back - changes the address to www.example.com and loads up the page correctly.
So, how can I get it to not break the back button? This is what I've got in my comments directive:
$scope.$on('$locationChangeStart', function(e, newUrl) {
// If moving off current page...
if ($scope.changingCommentsPage === false) {
$window.location.href = newUrl;
}
});
$scope.$on('$locationChangeSuccess', function() {
// Get current urlParams
var urlParams = $location.search();
// Get new comments if page has changed
if ($scope.page != urlParams.page || typeof urlParams.page === "undefined") {
$scope.changingCommentsPage = false;
$scope.page = urlParams.page ? urlParams.page : 1;
if ($scope.page < 1) return;
// Get comments
getComments($scope.model.page);
}
});

Ajax with history.pushState and popstate - what do I do when popstate state property is null?

I'm trying out the HTML5 history API with ajax loading of content.
I've got a bunch of test pages connected by relative links. I have this JS, which handles clicks on those links. When a link is clicked the handler grabs its href attribute and passes it to ajaxLoadPage(), which loads content from the requested page into the content area of the current page. (My PHP pages are set up to return a full HTML page if you request them normally, but only a chunk of content if ?fragment=true is appended to the URL of the request.)
Then my click handler calls history.pushState() to display the URL in the address bar and add it to the browser history.
$(document).ready(function(){
var content = $('#content');
var ajaxLoadPage = function (url) {
console.log('Loading ' + url + ' fragment');
content.load(url + '?fragment=true');
}
// Handle click event of all links with href not starting with http, https or #
$('a').not('[href^=http], [href^=https], [href^=#]').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
ajaxLoadPage(href);
history.pushState({page:href}, null, href);
});
// This mostly works - only problem is when popstate happens and state is null
// e.g. when we try to go back to the initial page we loaded normally
$(window).bind('popstate', function(event){
console.log('Popstate');
var state = event.originalEvent.state;
console.log(state);
if (state !== null) {
if (state.page !== undefined) {
ajaxLoadPage(state.page);
}
}
});
});
When you add URLs to the history with pushState you also need to include an event handler for the popstate event to deal with clicks on the back or forward buttons. (If you don't do this, clicking back shows the URL you pushed to history in the address bar, but the page isn't updated.) So my popstate handler grabs the URL saved in the state property of each entry I created, and passes it to ajaxLoadPage to load the appropriate content.
This works OK for pages my click handler added to the history. But what happens with pages the browser added to history when I requested them "normally"? Say I land on my first page normally and then navigate through my site with clicks that do that ajax loading - if I then try to go back through the history to that first page, the last click shows the URL for the first page, but doesn't load the page in the browser. Why is that?
I can sort of see this has something to do with the state property of that last popstate event. The state property is null for that event, because it's only entries added to the history by pushState() or replaceState() that can give it a value. But my first loading of the page was a "normal" request - how come the browser doesn't just step back and load the initial URL normally?
This is an older question but there is a much simpler answer using native javascript for this issue.
For the initial state you should not be using history.pushState but rather history.replaceState.
All arguments are the same for both methods with the only difference is that pushState creates a NEW history record and thus is the source of your problem. replaceState only replaces the state of that history record and will behave as expected, that is go back to the initial starting page.
I ran into the same issue as the original question. This line
var initialPop = !popped && location.href == initialURL;
should be changed to
var initialPop = !popped;
This is sufficient to catch the initial pop. Then you do not need to add the original page to the pushState. i.e. remove the following:
var home = 'index.html';
history.pushState({page:home}, null, home);
The final code based on AJAX tabs (and using Mootools):
if ( this.supports_history_api() ) {
var popped = ('state' in window.history && window.history.state !== null)
, changeTabBack = false;
window.addEvent('myShowTabEvent', function ( url ) {
if ( url && !changingTabBack )
setLocation(url);
else
changingTabBack = false;
//Make sure you do not add to the pushState after clicking the back button
});
window.addEventListener("popstate", function(e) {
var initialPop = !popped;
popped = true;
if ( initialPop )
return;
var tabLink = $$('a[href="' + location.pathname + '"][data-toggle*=tab]')[0];
if ( tabLink ) {
changingTabBack = true;
tabLink.tab('show');
}
});
}
I still don't understand why the back button behaves like this - I'd have thought the browser would be happy to step back to an entry that was created by a normal request. Maybe when you insert other entries with pushState the history stops behaving in the normal way. But I found a way to make my code work better. You can't always depend on the state property containing the URL you want to step back to. But stepping back through history changes the URL in the address bar as you would expect, so it may be more reliable to load your content based on window.location. Following this great example I've changed my popstate handler so it loads content based on the URL in the address bar instead of looking for a URL in the state property.
One thing you have to watch out for is that some browsers (like Chrome) fire a popstate event when you initially hit a page. When this happens you're liable to reload your initial page's content unnecessarily. So I've added some bits of code from the excellent pjax to ignore that initial pop.
$(document).ready(function(){
// Used to detect initial (useless) popstate.
// If history.state exists, pushState() has created the current entry so we can
// assume browser isn't going to fire initial popstate
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
var content = $('#content');
var ajaxLoadPage = function (url) {
console.log('Loading ' + url + ' fragment');
content.load(url + '?fragment=true');
}
// Handle click event of all links with href not starting with http, https or #
$('a').not('[href^=http], [href^=https], [href^=#]').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
ajaxLoadPage(href);
history.pushState({page:href}, null, href);
});
$(window).bind('popstate', function(event){
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) return;
console.log('Popstate');
// By the time popstate has fired, location.pathname has been changed
ajaxLoadPage(location.pathname);
});
});
One improvement you could make to this JS is only to attach the click event handler if the browser supports the history API.
I actually found myself with a similar need today and found the code you provided to be very useful. I came to the same problem you did, and I believe all that you're missing is pushing your index file or home page to the history in the same manner that you are all subsequent pages.
Here is an example of what I did to resolve this (not sure if it's the RIGHT answer, but it's simple and it works!):
var home = 'index.html';
history.pushState({page:home}, null, home);
Hope this helps!
I realize this is an old question, but when trying to manage state easily like this, it might be better to take the following approach:
$(window).on('popstate',function(e){
var state = e.originalEvent.state;
if(state != null){
if(state.hasOwnProperty('window')){
//callback on window
window[state.window].call(window,state);
}
}
});
in this way, you can specify an optional callback function on the state object when adding to history, then when popstate is trigger, this function would be called with the state object as a parameter.
function pushState(title,url,callback)
{
var state = {
Url : url,
Title : title,
};
if(window[callback] && typeof window[callback] === 'function')
{
state.callback = callback;
}
history.pushState(state,state.Title,state.Url);
}
You could easily extend this to suit your needs.
And Finally says:
I'd have thought the browser would be happy to step back to an entry that was created by a normal request.
I found an explanation of that strange browser's behavior here. The explanation is
you should save the state when your site is loaded the first time and thereafter every time it changes state
I tested this - it works.
It means there is no need in loading your content based on window.location.
I hope I don't mislead.

Code works when i put javascript alert in between anywhere

I have a function that runs on key tab press, it works fine when i put a javascipt alert in between the code, any kind of alert,if i remove the alert it stops working : my function
//Function to set the tab feture for focus to work properly on fields with autosuggestion(location and name)
function setFocusOnTab(name) {
var focusElement = "";
if(name == "name") {//For main contact field
if ($("#email").is(":visible")) {
$('#email').focus();
}
} else if(name == 'location_name') {//For main contact field
$("#country").focus();
} else {//For extra contact field
var outputDataCurrentVal = name.lastIndexOf('record_');
if(outputDataCurrentVal < 0) {
//ADDTIONAL CONTACT TAB
var outputDataCurrentName = name.lastIndexOf('_name_');
if(outputDataCurrentName >= 0) {
//Replacing the name to get location name.
locName = currentName.replace("_name_","_designation_");
focusElement = locName;
} else {
var outputDataCurrentLoc = name.lastIndexOf('_location_');
if(outputDataCurrentLoc >= 0) {
//Replacing the location name to get country name.
countryName = name.replace("_location_","_country_");
focusElement = countryName;
}
}
} else {
//Extra CONTACT TAB
var outputDataCurrentName = name.lastIndexOf('_name_');
if(outputDataCurrentName >= 0) {
//Replacing the name to get location name.
locName = currentName.replace("_name_","_location_");
focusElement = locName;
} else {
var outputDataCurrentLoc = name.lastIndexOf('_location_');
if(outputDataCurrentLoc >= 0) {
//Replacing the location name to get country name.
countryName = name.replace("_location_","_country_");
focusElement = countryName;
}
}
}
$("#" + focusElement).focus();
return false;
}
}
Sounds like you need something to halt your code, which is what alert() does.
You may need a callback instead.
What might be happening with alert() is that calling it causes the current window to lose focus (as focus moves to the new pop-up dialogue box), and after it's finished it re-focuses the window. This will trigger focus and blur events which might confuse your script, and in Safari the window may not re-focus at all.
It's not clear to me what you are doing here... how are you attaching this code to a tab key event? What event is supposed to be cancelled by the return false;? If you are using keypress, then that simply won't get called for the Tab key in IE, Safari or Chrome. If you are using keydown, then cancelling the event won't prevent the tabbing in Opera. And what about Shift-Tab?
Reproducing/altering browser keyboard behaviour is hard: it's much better not to if there's any other way. For making controls like a drop-down suggester work you are probably much better off just setting the declarative tabIndex on the elements concerned and letting the browser work out how to sort out the tabs from there.
I should write something on this post. I read so many blogs and post but couldn't get the right solution from anywhere else. Even in this post, I looked more detail and tried each of solution.
Finally reading the answer of bobince, I could figured out the solution. In my case, I have set the focus to another textbox ( not required type) and later when I finish my job, I set back focus to original one. So the morel story is we just need to set focus somewhere else from current element which actually done by alert and I have replaced that on by setting the focus on non required element.

Trigger function based on result of custom function Referring URL

I need to use JavaScript (jQuery if applicable) to trigger my modal call if the result of my function is true and the referring URL is not of the domain.
The desire is that the user visits the main splash page and as long as they have not been redirected there by the site itself (via timeout on a session, invalid login credentials, etc) it displays the message so:
function showModalIf() {
if (checkFunction) {
if(////// REFERRING URL not from this site)
Trigger Modal Call
else
Don't Do anything else
}
}
Assuming you use jQuery UI Dialog to show the modal
function checkReferrerExternal() {
if (!document.referrer || document.referrer == '') return false;
var regex = /^https?:\/\/\/?([^?:\/\s]+).*/;
var referrermatch = regex.exec(document.referrer);
var locationmatch = regex.exec(document.location);
return referrermatch[1] != locationmatch[1];
}
function showModalIf() {
if (checkReferrerExternal()) {
//show jQuery UI Dialog modal or replace with whatever
$("div#dialog").dialog('open');
}
}
Check demo page http://jsbin.com/efico
If you are talking about forced redirection in the code, and not just a hyperlink click from elsewhere in the site, you could add a query string parameter on your redirection and check that way. Another option is to set a cookie and check for the cookie in javascript.
Here is a nice link on cookie handling in Javascript:
Javascript - Cookies
And here's one for parsing query string params/hashes in Javascript as well:
Parsing The Querystring with Javascript
Hope this points you in the right direction :)

Categories

Resources