I am working on a site that has dynamic content.
When you click an article, it changes to address using the push state.
Example:
http://www.some-site.com/news/ - Before clicking a news item
http://www.some-site.com/news/dynamic-url/ - after clicking news item
But as pushstate does not work in IE or older browsers, I've rewritten it to use jQuery.address so it changes the hash in the url instead only for IE.
The problem now, is say someone sends a link to the site to a friend that they copied from Chrome and their friend uses IE, it will start appending the new has to that url.
Example:
http://www.some-site.com/news/dynamic-url/ - URL sent to friend
http://www.some-site.com/news/dynamic-url/#!/dynamic-url - URL after friend visits the site
So, I'm stuck on how to rewrite/redirect them. As, the hash never gets sent to Apache.
I've seen on twitter, they do exactly what I want, but I am unable to figure out how.
https://twitter.com/#!/google gets redirected to https://twitter.com/google and it works in IE.
Any help is much appreciated and if you don't understand please ask me to elaborate.
As suggested by David Thomas, here is the function.
var permalink = function(title, id, permalink){
var current = siteUrl + type + (order ? '/orderBy/' + order : '');
var newUrl = current + '/' + permalink + '/';
if(jQuery.browser.msie){
newUrl = '/' + permalink + '/';
jQuery.address.value(newUrl);
}
else{
stateNum++;
window.history.pushState({state: stateNum}, title, newUrl);
}
jQuery('title').html('SITE - ' + title);
}
What you need to do is either use a plugin (like jquery history) or make an event yourself to check the hash changes. Then, you read the hash (you strip the "!") and then handle the hash how ever you need. You might want to do ajax with it (such as load the domain / hash) and put the content somewhere on the page.
Is that clear?
After thinking it through for a while, I could only find one solution.
I'll post it here in case anyone is in a similar situation.
My solution, was a little hacky. If the browser is IE and has a fragment of url after a certain point, I count that as the name of news item. Once I have the name, I redirect them to the suitable url.
var permalink = function(title, id, permalink){
var current = siteUrl + type + (order ? '/orderBy/' + order : '');
var newUrl = '/' + permalink + '/';
if(jQuery.browser.msie){
jQuery.address.value(newUrl);
}
else{
current = siteUrl + type + (order ? '/orderBy/' + order : '');
newUrl = current + '/' + permalink + '/';
stateNum++;
window.history.pushState({state: stateNum}, title, newUrl);
}
jQuery('title').html('SITE - ' + title);
}
jQuery(document).ready(function(){
jQuery.address.crawlable(true);
if(jQuery.browser.msie){
if(jQuery.address.value() == '/'){
var currentPermalink = window.location.toString();
currentPermalink = currentPermalink.split(type);
if(currentPermalink[1] !== '/'){
window.location = siteUrl + type + '/#!' + currentPermalink[1];
jQuery.address.value(newUrl);
}
}
}
});
Related
I'm brand new to webdev, I'm trying to build a web app that gets a new quote whenever the button #getQuote is clicked.
This is my my js code:
$(document).ready(function() {
// function get_new will get a new JSON object
function get_new() {
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content.slice(3, -6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function() {
$(this).attr('href', 'https://twitter.com/intent/tweet?text=' + '"' + quote + '" - ' + author).attr("target", "_blank");
});
});
}
// calling function to appear as default
get_new();
// when clicked, get new quote
$('#getQuote').click(function() {
get_new();
});
});
Any help would be appreciated guys.
Here's the codepen for anyone interested:
https://codepen.io/tadm123/pen/YNvdyr
As others have pointed, it's just a cache issue on codepen.
Add this line to your code to set cache false:
$.ajaxSetup({ cache: false });
Be careful using this in a live environment, you dont want to affect all your ajax requests with cache:false. So I'd recommend you using a normal jQuery ajax call and set the property cache to false specifically to this function only:
$.ajax({
cache: false,
url: "/path/to/file.json",
dataType: "json",
success: function(data) {
...
}
});
Your code is 100% right. It just so happens that the browser is caching the result of the url you're accessing. I noticed that Codepen was caching the result and my browser was caching it too when I tested it with files on my computer. So after it hits that URL the first time, it thinks something along the lines of "Oh, I've already gone to this URL and I already know what the result is. So to save time, I'll just give it the same data as before."
To combat this (this might be considered hacky?), add the current time to the end of the URL (because the time will always be different) like so:
function get_new(){
var currentDate = new Date().getTime(); // create new date
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&date=" + currentDate, function(a) { // add it to end of URL
var quote = a[0].content.slice(3,-6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function(){
$(this).attr('href', 'https://twitter.com/intent/tweet?text='+ '"'+ quote + '" - ' + author).attr("target","_blank");
});
});
}
Also sometimes the result will come slowly, but I think that's because of the speed of the server your requesting the quotes from. Another challenge can be to have a loader show while it's getting a quote from the server.
Put cache false in your URL. This is because you are getting same data again and again
https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&cache=false&callback
Close... to get it to work with the console closed, the $.ajaxSetup({ cache: false }); didn't work. However, randomizing the URL did:
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&cache="+Math.random(), function(a) {
I have the following code which works on the first time around:
$("#CompDD").change(function () {
//var parts = (window.location.pathname.split("/"));
var ctrlName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var actnName = '#ViewContext.RouteData.Values["Action"].ToString()';
var url = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//delete ctrlName;
// delete actnName;
//window.location = ($(location).attr('href') + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//window.location = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//$(location).attr('href', url);
window.location.href = url;
//alert(ctrlName + "\n" + actnName);
});
However on subsequent changes of the drop down in question (#CompDD) it will add another controller/action to the end of the link, ex. it adds another "Patrons/Index" to the end of the existing "Patrons/Index", thenit adds the searchsrting variables etc.
Please excuse the comments and stuff on my code. How do i get Jquery (or javascript) to redirect without appending the controller name and action names over and over, or whats the best way to do this?
EDIT: Such an easy fix! I had to add the root slash to the URL string, example this worked:
var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
Notice the forward slash at the start of the string I construct....Yikes!
Use the Url.Action helper method to build path to action methods.
$("#CompDD").change(function () {
var baseUrl="#Url.Action("Home","Search")";
alert(baseUrl);
// Now append your query string variables to baseUrl
// Ex : baseUrl=baseUrl+"?searchString=testing";
window.location.href=baseUrl;
});
Assuming you want to navigate to the search action method in Home controller.
function RedirectUrl() {
if (domElement.textfor.val() == "Index") {
window. location.href = E_host.AppVar.AppHost + "/Home/index";
}
}
I'm trying to route to a different page in Rails using Javascript (Coffeescript).
This is my code:
# go to edit page
serverused = window.location.host
newurl = serverused + '/sites/' + node.id + '/edit'
alert newurl
window.location = newurl
alert window.location
return
The alert new url = "localhost:3000/sites/2/edit"
The alert window.location (which it shouldn't even get to) shows: "localhost:3000/sites/tree#node-5" - which is the current url.
Thanks for the help!
Your newurl probably needs a http:// or https:// in front of it. Or you can grab the protocol from the current location:
newurl = window.location.protocol + '//' + serverused + '/sites/' + node.id + '/edit'
You can also use string interpolation in Coffeescript (requires double quotes):
newurl = "#{window.location.protocol}//#{serverused}/sites/#{node.id}/edit"
I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '  says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
I have a url redirect script that works very well, but i want some change in it.
when i redirect outgoing link then at the end of redirected url i got something like '#lcinside'
example
http://dl.dropbox.com/u/36139836/unknown.html?urlc=http://imgur.com/
goes to
http://imgur.com/#lcinside
but i want to put #lcinside before url start.
example
#lcinsidehttp://imgur.com
i want to put adf url redirect link instead of #lcinside.
how can i put #lcinside before url .
below is script.
please help me.
<script>
function gup(sName)
{
sName = sName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var sRegEx = "[\\?&]" + sName + "=([^&#]*)";
var regEx = new RegExp(sRegEx);
var aResult = regEx.exec(window.location.href);
if(aResult == null)
{
return "";
}
else
{
return aResult[1];
}
}
if(gup("urlc") != "")
{
window.location = gup("urlc").replace("lcamp", "&") + "#lcinside";
}
</script>
If you are just trying to scrub the referrer, maybe you should use meta refresh
<meta http-equiv="refresh" content="1;url=http://imgur.com/#lcinside">