Ajax Loading of Page Without changing the loaded content after refresh - javascript

The situation is that I have links:
Edit Account Info - that points to http://example.com/user/edit
I setup a javascript that will only fetch information in the controller then will load it in a template.
I have this code that does the eventhandling
$("#lnkEditUser").on("click",
function()
{
some.settings.edit_profile();
return false;
})
What it does, is that it replaces the content of a div with the template,
so I have it loaded, the template and the details from the controller(from the model) via ajax calls. The problem is that when I try to refresh the page, the content would be its default. Is it possible that when I click on the link the URL will then change to something like:
http://example.com/user#edit
So even when I refresh the page, the content loaded via ajax will be the same?
If I remove the #edit, it'll be the default?

Correct me if i did this right, or if there is a better way to do it..
first I check if the hash exist, then get the value of the hash, assigned it to variable hash then i removed the hash, maybe i can do also do this replace("#", ""). I realize other stuffs while i'm typing this like i should have been converted it hash to string right on the assigning of value. But anyhow, this is how I did it.
activeTemplateViaHash : function() {
if (window.location.hash) {
var hash = window.location.hash;
hash = hash.toString().substr(1, hash.toString().length-1);
var method = new Function('some.settings.' + hash + '()');
method();
}
},

Try doing this:
activeTemplateViaHash : function() {
if (window.location.hash) {
var hash = window.location.hash;
hash = hash.replace("#", "");
var method = some.settings[hash]; //find the hash method
if(method) { //if the method exists then run it
method();
}
else {
alert(hash + " function doesn't exist!");
}
}
},
But instead of relying on hashes like that, I would use localStorage or COOKIES to store user settings easily.

Related

JavaScript: How to save the state of your website structure to a link (or hash link)

In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).
Note: I need this in 'pure' JavaScript.
There are several ways you can achieve this. One of the following options may work for you.
Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.
document.addEventListener("DOMContentLoaded", function(event) {
// Website has loaded.
var hash = location.hash
// Check if the hash exists and is popup.
if (hash && hash === 'popup') {
// Show your popup
}
});
Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var popup = getParameterByName('popup');
// Check if we have the popup parameter.
if (popup) {
// Show popup
}
Suggest using
http://www.mywebsite.com#show-pop-up
instead of
http://www.mywebsite.com/show-pop-up
then using
if(location.hash === '#show-pop-up') {
// show your popup
}
on page loaded.

taking the # out of url on location.hash

function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.

Triggering Script VIA URL variable

As of now, on my page, the following html is working fine to trigger the following javascript function :
Link to other section
What I'd like to do is to have the javascript function triggered on page load when a specific variable is added to the URL. (Instead of having it as a link on the page)
For example, if url is www.mysite.com, page loads normally. If URL is www.mysite.com/?variable=1 , the script is triggered and user is redirected.
(I know there are other ways to redirect a user to another page, but I need to use this specific script, since the destination is dynamic from one type of user to another.)
I have very basic javascript knowledge and can't make the code I found here work : Triggering Script VIA URL . What they're doing is triggering a fancybox through URL variable. I believe that it's the same thing I want to achieve here. I'm just not to sure how to modify the code to go from "fancybox" to "redirectToOtherSection()"
var $j = jQuery.noConflict();
$j(document).ready(function() {
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('globe=1') != -1) {
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
}
}); // extra curly bracket removed
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
They are using jquery, not sure if jquery is needed in my case?
Any help is much appreciated!
Thanks
based on what you've said you dont need jquery, try
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('variable=1') != -1) { // where variable 1 is wqhats in you url
redirectToOtherSection();
}

What's the best way to force a hashchange?

My website uses hashchange-triggered AJAX (to make it more bookmark-friendly). The problem I am having is that when I click "submit" in a form, all the form data that is serialize()'d to be sent via $.post() gets lost. I know this because I get the "Flag 1" alert after I click submit, and various other tests (alerting, echoing, etc.) show this to be true.
Here's my current code:
$(document).ready(function() {
var data = '';
var hash = '';
newPage();
alert('Flag 1');
$(window).bind('hashchange', function() {
hash = window.location.hash;
if (hash == '') {
path = window.location.pathname;
hash = '#' + path.replace(/^\/+/, '');
}
data += '&func=' + hash;
var xhr = $.post(hash, data, function(result) {
$("maincontent").html(result);
})
.done(newPage);
});
// Initialize vars and handle new form elements
function newPage() {
data = '';
$('form').submit(function() {
data = $(this).serialize();
// Flag 2 - What do I do here?
});
}
// Load ajax content on first run of document
if ($('#maincontent').html() == '')
$(window).trigger('hashchange');
});
What I am trying to do is manually fire a hashchange event while also changing the URL. The trouble is that if I just set window.location.hash = $(this).attr('action'); then return false; where the "Flag 2" comment is, then I wind up getting unwanted trash in the URL, possibly due to the hashmark being encoded for a URL (...%23, etc).
I am wondering what the best way to set the hash is, and whether there is a simpler way to do what I am trying to do to begin with.
(I'm also open to comments suggesting alternate approaches for the style of navigation I am trying to achieve)
Well, I understand there are lots of errors doing this. But we have alternative options for this you will surely like:
jQuery History Plugin : http://plugins.jquery.com/history/ (Demo: http://4nf.org/)
History JS: https://github.com/browserstate/history.js/
But I would recommend HTML5 history.pushState if you are willing to avoid older browser support. (Demo: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
Good luck!!

Javascript window.location search for "#" never returns true

I'm trying to set up a redirector so that when my AJAX functions change the hash part of the URI, the link is still directly accessible should it be copied and pasted. My current function is below; however, it always returns false!
//If a hash is found, redirect it
var current_uri = String(window.location);
if (current_uri.search('/\#/') != -1) {
var current_uri_array = current_uri.split('#');
window.location = current_uri[1];
}
How can I change the code to make this work? Is there a better way of doing this?
Code updated to:
if (window.location.hash) {
window.location = window.location.hash.substring(1);
}
Which worked.
Try using window.location.hash directly ;)

Categories