Rails javascript window.location not working - javascript

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"

Related

How can I add a parameter to my url, without reload the page?

I have this url http://localhost:1234/pag1
I want to be like below when I click on the div:
http://localhost:1234/pag1?fare=standar
and I have an onclick event function:
<div id="" onclick="addUrl();"> </div>
And the js code:
<script type="text/javascript">
function addUrl() {
var url = window.location.href;
window.location.hash = '?fare=standar';
};
</script>
This give me this result:
http://localhost:1234/pag1#?fare=standar
And I don't Know how to remove the (#). I only need to add the parameter to the url, without refresh the page.
Suggest me! Thank's.
Use window.history.pushState( {} , '', '?fare=standar' );
This should update the url without refresh.
You can also do a bit of reseach on pushState as the implementation can differ.
window.location.hash always put "#" in url
you can use to push paramter in url by using this function
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url;
}
i hope this will helpful to you
Try this
HTML
<div onclick="addUrl()"> </div>
Javascript
<script type="text/javascript">
function addUrl() {
var url = window.history.pushState( {} , '', '?fare=standar' );
</script>
Quick Explanation : When user clicks on div, URL will update without refreshing the page.
Hope this will work for you,
thank you :-).
Try this
var myURL = document.location;
document.location = myURL + "?a=parameter";
Or
location.hash = 'a=parameter'
Or without reloading the page
window.history.pushState("object or string", "Title", "new url");
Or without reloading the page
window.history.replaceState(null, null, "/another-new-url");
Why dont you use jQuery? I prepared sample like here in JsFiddle:
$("#clickableDiv").click(function(){
var url = "http://localhost:1234/pag1";
var parameter = "fare=standar";
$("#AppendUrl").text(url+ "?" + parameter);
});

Jquery or Javascript Redirect to Controller/Action

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";
}
}

JavaScript window.location.href not working

I'm trying to redirect to a new URL using window.location.href which does not seem to work for a particular URL.
The page URL is: http://localhost:37368/Office/Search/c2VhcmNoaWRzPTEyMiwxMjIsMTI0LDE1OCwzNzl8bG9jYXRpb25pZHM9MSwyfGZyb21pZHM9fHRvaWRzPQ==
Upon a button click, something happens using an AJAX post, and the URL is changed, via JavaScript, to http://localhost:37368/Office/
However, the page always redirects back to the previous one.
The JS code:
onClear: function (event) {
//.... omited for purpose of question
var $controller = (event.data.object.settings.controller === undefined) ? '' : event.data.object.settings.controller
$new_url = window.location.protocol + '//' + window.location.host + '/' + $controller;
window.sessionStorage.clear();
window.location.href = $new_url;
}
Try to add to new URL some random parameter to avoid caching or other bugs:
$new_url = window.location.protocol + '//' + window.location.host + '/' + $controller + '?r=' + ("" + Math.random()).substr(2, 4);

Rewrite URL hash to get variable

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);
}
}
}
});

Making a function work in HTTP and HTTPS

I have this Javascript code I inherited from another developer. I am very new to Javascript.
The problem I'm having is that it won't work when the user is in HTTPS. Is there a workaround for this problem?
var tier1CategoryLink = "http://" + window.location.hostname + "/categories/";
$("#as_Placeholder").load(tier1CategoryLink + " .SubCategoryList > ul", function(){
$('#tier1').find('option').remove().end().append('<option>Make</option>');
$("#as_Placeholder ul li").each(function(){
var thisText = $(this).children("a").text();
if ((thisText != "All Products") && (thisText != "Best Selllers") && (thisText != "Chromoly Flywheel Combo Sale") && (thisText != "New Arrivals") && (thisText != "On Sale") && (thisText != "Needs Categories")) {
$("#tier1").append("<option value='" + $(this).children("a").attr("href") + "'>" + thisText + "</option>");
}
});
});
Use window.location to determine user's current protocol and adjust accordingly:
var tier1CategoryLink = window.location.protocol + "//" + window.location.hostname + "/categories/";
Or just use relative URL:
var tier1CategoryLink = "/categories/";
I guess you want to say that you get a java-script error in the browser. And that is expected too. When the user is in https then you have to amend the java-script to include https. For eg your first line must look like this:
var tier1CategoryLink = "https://" + window.location.hostname + "/categories/";
EDIT: Moreover you can have a look at this to solve your issue.
Detect HTTP or HTTPS then force HTTPS in JavaScript
Easiest solution is to just use double slashes
var tier1CategoryLink = "//" + window.location.hostname + "/categories/";
Details in spec Section 5.2

Categories