execute a function after redirecting - javascript - javascript

Okay, i have a simple button on my page (MyPage) which fades out the current div (fade 1) and fade in another one (fade 2). I have now realised that there might be chances that i would want to go to that page (fade 2) from somewhere else directly. I am able to redirect my page by window.location. However i also want that if that link was pressed (from some other random page), go to page (fade 1) and then fadeOutthe current div and fadeIn another one (fade 2).
Hope this isn't too confusing. This is the code i am using to get to the page (MyPage):
$('#fav').click(function(){
window.location = 'production/produc_order.php';
$('#view_production').fadeOut('slow');
$('#create_order').fadeIn('slow');
})

If you don't want to or can't re-code your page to support AJAX, the other old-school option is to pass a parameter in the URL as a hint to the refreshed page. (You can hide it by making the redirect a POST if you feel it's really necessary, or use a cookie technique. The point is that the refreshed page needs a token of some form from the prior page.)
eg:
$('#fav').click(function(){
window.location = 'production/produc_order.php?create=1';
})
and put the fade code inside the $(document).ready() function, with a check for the create parameter, cookie or whatever.
I'll agree with #remibreton though, using AJAX is the more hip, modern method.

Changing the window.location will kill all scripts currently running in the browser.
Your only other solution is getting a page via AJAX and run a callback function to execute when the content is loaded. Here is something to get you started.
Also, jQuery as a nice .ajax() method to easily perform AJAX requests and associate callbacks to successful and failed requests.

you can do it with sessionStorage()
$('#fav').click(function(){
sessionStorage.setItem("reloading", "true");
window.location = 'production/produc_order.php';
});
var reloading = sessionStorage.getItem("reloading");
if(reloading == true) {
sessionStorage.removeItem("reloading");
$('#view_production').fadeOut('slow');
$('#create_order').fadeIn('slow');
}

Related

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

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.

Changing div#content without reloading using Jquery

I have been reading this board all night and I haven't found anything that quite hits the answer I need on the head, so I will ask.
Here's the basic idea of what I'm doing.
On Page Load, fade in, and display the default page.
User Clicks Navigation Link (a.navLink).
div#content fades out, calls a function to redirect.
div#content fades in with new content.
I have it at about 90% however, it's not quite right.
I am using a PHP Switch to manage content on the site using the $_GET superarray. My basic switch structure is as follows:
switch( $_GET['page'] ){
default:
//DISPLAY HOME PAGE
break;
case "story":
// DISPLAY STORY
break;
case "contact":
// DISPLAY CONTACT
break;
}
and so on...
The JQuery I'm using to perform the Fade In / Fade Out Action is as Follows:
$("#content").css("display", "none");
$("#content").fadeIn(1000);
$("a.navLink").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("#content").fadeOut(500, redirectPage);
function redirectPage() {
window.location = linkLocation;
}
});
The current code successfully fades out, changes pages and fades back in, but the problem is the site reloads, causing the rotating banner I have at the top of the page to restart. Also, the page starts back at the top as if the site had just been loaded. I know that this likely needs an AJAX function, but I have very little experience using AJAX (I often avoid it like the plague).
It is very important that I use the Switching structure I have in place, and I haven't had much success hashing it. The URL that I would be working with is DOMAIN.COM/index.php?page=pageName. Again, this structure is very important and cannot be changed.
Any insight on this would be great.
(Again, I understand this question type may have been asked before, but i feel that I need one line at most, and I'm trying to find out what that is)
Instead of
window.location = linkLocation;
Use Ajax to re-load only #content:
$( "#content" ).load(linkLocation, function(){
$('#content').fadeIn(500, function(){
// do something when the re-load is finished
});
});
You can't change the URL of the window via AJAX, but you could change window.location.hash. Others (in the comments) have mentioned using the history API.

redirect using javascript without flash

I trying to do the following:
I want to redirect to another page using javascript, but I want the page (that we redirect to) to fade in instead of being redirect to aggressively. How can Iget that done using jquery?
I tried the following:
$('.splash').hide();
$('.splash').fadeIn(2000,
function() {
setTimeout(
function() {
document.location.href = 'test.html';
},100)
<div class = "splash"></div>
Well you could $('html').fadeOut(); the current page you are on, then do your redirect. But that second page would have to have it's own $('html').fadeIn();
There is no way to push a jQuery execution onto a totally separate page unfortunately :/
You could try loading the page with $.load() AJAX style also.

Detect first page load with jQuery?

I need to detect the first time a page loads in jQuery so that I can perform some actions only when the page loads the first time a user navigates to that page. Similar to server side code page.ispostbasck. I have tested $(document).ready and it fires every time the page loads so this will not provide what I need. I have also tried the jQuery Load function - it also fires every page load. So by page load an example is that I have an HTML input tag on the page of type button and it does not fire a postback (like an asp.net button) but it does reload the page and fires $(document).ready
Thanks
You will have to use cookie to store first load information:
if (! $.cookie("cookieName")){
// do your stuff
// set cookie now
$.cookie("cookieName", "firstSet", {"expires" : 7})
}
Note: Above example uses jQuery Cookie plugin.
An event doesn't exist that fires only when the page is loaded for the first time.
You should use jQuery's .ready() event, and then persist the fact that you've handled a first time page load using your method of choice (i.e. cookie, session variable, local storage, etc.).
Note: This method will never be fool proof unless you can store this information at the user level in a DB. Otherwise, as soon as the user clears their cookies, or whatever method you choose, the "first time loaded" code will fire again.
I just ran into this problem and this is how I handled it. Keep track of the first time the page loads by using a variable initialLoad:
var initialLoad = true;
$(document).ready(function() {
...
...
...
initialLoad = false;
});
Then in other functions, you can do this:
if (initialLoad) {
//Do work that is done when the page was first refreshed/loaded.
} else {
//Do work when it's not the initial load.
}
This works well for me. If the user is already on the page and some jQuery functions run, I now know if that user just loaded the page or if they were already on the page.
The easy solution is to use jQuery ‘Once’ plugin
$(element).once('class-name', function() {
// your javascript code
});

Categories

Resources