Adding a parameter to an extended url with jQuery? - javascript

I'm using a script to add parameters to a URL to use with a if statement for a layout change. It works with a structure like this:
/Computers/Desktops
on click to change layout:
/Computers/Desktops?param=list
and
/Computers/Desktops?param=grid
I'm using a filer that adds parameter, then the layout will change between something like this:
/Computers/Desktops?param=list&fss=HP+2GB
and on click:
/Computers/Desktops?param=grid&fss=HP+2GB
This works well, but I need to make this work for another structure that looks like this:
/Computers/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?prodid=30811
Here I want to add the parameter before ?prodid=30811 so the layout changes on click between
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=list&prodid=30811
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=grid&prodid=30811
I hoped I just could change FSS in my script to prodid, but this doesn't work. So why doesn't it work and why, and how do I do this instead? My if/else script already works, I just need the correct URL from the buttonclick.
$('.click3').on('click', function() {
console.log("Clicked");
var baseUrl = window.location.href.split("?")[0];
var fss = getParametersByName("fss");
var params = getParametersByName("fss");
if (params == "list")
param = "grid";
else
param = "list";
var newUrl = baseUrl + "?param=" + param;
if ((fss).length > 0)
newUrl = newUrl + "&fss=" + fss;
window.location.href = newUrl;
function getParametersByName(name) {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
});

Related

MVC 4 Pass value from Javascript to Controller

In my view, I have a javascript function to handle a select event on a pie chart. The function is shown below:
function selectHandler() {
var selectedItem = visualization.getSelection()[0];
if (selectedItem) {
var val = data.getFormattedValue(selectedItem.row, 0);
location.href = '/Tickets';
}
}
Currently I am on the Home Controller in the Groups View. I want to navigate to the Index View of the Tickets Controller while passing the selected value from the javascript variable "val". How would I go about doing this?
Are you intending to manually navigate the user?
If you're looking for a redirect JavaScript way, then you would do something as simple as...
location.href = '/Tickets?value=' + val;
Now this may not work for everything. For example, if location.href already contains a '?', and you need to maintain that context, then you need to use '&'. Maybe your app lives in a Virtual Directory.
You might do something like...
var newUrl = location.href;
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
newUrl += val;
This allows you maintain any existing context as well.
If you expect the ticket to already be defined, you might need to remove that from the query string, if it already exists.
In that case then you might want to do something like...
var params = location.search.substring(1).split('&'),
paramToRemove, indexOfValue,
hasSearch = false,
param;
for (var i = 0, len = i; i < len; i++)
{
param = params[i];
indexOfValue = param.indexOf('value');
hasSearch = param.indexOf('?') === 0;
if (indexOfValue === 0 || (indexOfValue === 1 && hasSearch ))
{
paramToRemove = params[i];
break;
}
}
var newUrl = location.href;
// Remove old value
if (paramToRemove) newUrl = newUrl.replace(paramToRemove, hasSearch ? '?' : '');
// Add proper search char
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
// Add new value
newUrl += val;
location.href = '/Tickets?val=' + val;
//On page load the server will generate the URL for you.
var ticketURL = '#Url.Action("Index", "Tickets")';
//Append the value to the URL
ticketURL = ticketURL + '?val=' + val;
//Do your stuff!
Since, you are calling Controller methods from javascript. You should make an POST ajax call to Ticket Controller and passing Action method name also.
Your code would be like this:
return $.post('/Ticket(ControllerName)/Index(method name)/',parameters here);
Inside API Controller, Index method will accept the same param which we are passing from our javascript.
ActionResult Index(parameter){...}

"Cannot find function replace" errror when trying to replace part of a string

I need a way to replace part of a string with another string using Google Apps Script. I tested the following and it worked:
function test(){
var value = 'https://plus.google.com/117520727894266469000';
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
function googlePlus(value){
var apiKey = ScriptProperties.getProperty('apiKey');
var re = 'http://'
var theURL = value;
Logger.log('Google+ is called: ' + value);
var replacingItem = 'https://';
var theURL = theURL.replace(re, replacingItem);
Logger.log('Google+ Values 2: ' + value + ' : ' + theURL + ' after ' + replacingItem);
return imageURL;
}
But, when I embedded into the following code, it did not work. Any idea?
//If a Google+ column was not specified,put a flag.
if (googleColumn && column == googleColumn) {
if (value == ""){
columns.push(nogoogleColumn);
values.push(flag);
var googleimageURL="";
} else {
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
}
The script did not work as I wish. It seems to stop at line:
var theURL = theURL.replace(re, replacingItem);
Additional information: Google notified me with the following message
onFormSubmit
TypeError: Cannot find function replace in object https://plus.google.com/117520727894266469000. (line 536) formSubmit
I found the mistake. It is Type Error. value in the second block is not a "string", while the first block is a "string". Hence to fix the second block, I need to use:
var value = value.toString();
before passing to googlePlus(value)

Modifying a query string without reloading the page

I am creating a photo gallery, and would like to be able to change the query string and title when the photos are browsed.
The behavior I am looking for is often seen with some implementations of continuous/infinite page, where while you scroll down the query string keeps incrementing the page number (http://x.com?page=4) etc.. This should be simple in theory, but I would like something that is safe across major browsers.
I found this great post, and was trying to follow the example with window.history.pushstate, but that doesn't seem to be working for me. And I'm not sure if it is ideal because I don't really care about modifying the browser history.
I just want to be able to offer the ability to bookmark the currently viewed photo, without reloading the page every time the photo is changed.
Here is an example of infinite page that modifies query string: http://tumbledry.org/
UPDATE found this method:
window.location.href = window.location.href + '#abc';
If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.
function insertUrlParam(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
// to remove the specific key
export function removeUrlParameter(paramKey) {
const url = window.location.href
console.log("url", url)
var r = new URL(url)
r.searchParams.delete(paramKey)
const newUrl = r.href
console.log("r.href", newUrl)
window.history.pushState({ path: newUrl }, '', newUrl)
}
Old question, modern answer to help future devs; using the URL interface:
const url = new URL(window.location);
url.searchParams.set('key', value);
window.history.pushState(null, '', url.toString());
This makes sure you really only change the desired query-parameter.
Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:
//function to remove query params from a URL
function removeURLParameter(url, parameter) {
//better to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
//function to add/update query params
function insertParam(key, value) {
if (history.pushState) {
// var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
var hash = window.location.hash
//remove any param for the same key
var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);
//figure out if we need to add the param with a ? or a &
var queryStart;
if(currentUrlWithOutHash.indexOf('?') !== -1){
queryStart = '&';
} else {
queryStart = '?';
}
var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
window.history.pushState({path:newurl},'',newurl);
}
}
I've used the following JavaScript library with great success:
https://github.com/balupton/jquery-history
It supports the HTML5 history API as well as a fallback method (using #) for older browsers.
This library is essentially a polyfill around `history.pushState'.
If we simply want to update the query parameter without touching other parts of URL, there is no need to build the URL again. This is what I use:
const addQueryParam = (key, value) => {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({}, '', url.toString());
};
const getQueryParam = (key) => {
const url = new URL(window.location.href);
return url.searchParams.get(key) || '';
};
Since everyone answering this seems to forget the hash, I want to add the code I'm using to keep all URL parameters:
const urlParams = new URLSearchParams(window.location.search);
/// Change some part of the URL params
if (history.pushState) {
const newurl =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
"?" +
urlParams.toString() +
window.location.hash;
window.history.replaceState({ path: newurl }, "", newurl);
} else {
window.location.search = urlParams.toString();
}
Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.
I thought I'd add a bit to Fabio and Aram's answers. I thought I might sometimes like to preserve the hash in the url. But usually not, so I set that parameter to default to false.
replaceState still does not set the page title on Chrome. So I added a couple lines to change the title, if one is provided.
function insertUrlParam(key, value, title = '', preserve_hash = false) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname
+ '?' + searchParams.toString();
if(preserve_hash) newurl = newurl + window.location.hash;
let oldTitle = document.title;
if(title !== '') {
window.history.replaceState({path: newurl}, title, newurl);
if(document.title !== title) { // fallback if above doesn't work
document.title = title;
}
} else { // in case browsers ever clear titles set with empty string
window.history.replaceState({path: newurl}, oldTitle, newurl);
}
}
}

window.location.url Javascript

I'm splitting the current url into pieces but I'm doing something wrong with this part to get the current url. How can I solve this?
var url = window.location.url;
I'm trying to get the current url from the page. This is my function
function split(){
var url = window.location.url; // This part is not correct
var firstSplit = url.split('?')[1];
var name = firstSplit.split('&')[0];
var age = firstSplit.split('&')[1];
var parName = name.split('=')[0];
var nameName = name.split('=')[1];
var parAge = age.split('=')[0];
var ageAge = age.split('=')[1];
document.getElementById("nameId").innerHTML=naamName;
document.getElementById("ageId").innerHTML=leeftijdAge;
}
Use href:
window.location.href
For example running it on current SO page gives:
console.log(window.location.href);
this:
http://stackoverflow.com/questions/10783322/window-location-url-javascript
Add the following script to a page; it will display all the properties of the page's url:
document.write("<li>location.href = " + location.href);
document.write("<li>location.protocol = " + location.protocol);
document.write("<li>location.host = " + location.host);
document.write("<li>location.hostname= " + location.hostname);
document.write("<li>location.port = " + location.port);
document.write("<li>location.pathname = " + location.pathname);
document.write("<li>location.hash = " + location.hash);
document.write("<li>location.search = " + location.search);
better answer found here: https://gist.github.com/jlong/2428561
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
You can access different parts of the URL directly by using different properties on window.location.
The full URL is window.location.href, but you seem to be more interested in the query string (the part after the question mark) which you can access with window.location.search
A list of other properties is can be found in the MDN article about window.location.
Try
var url = window.location.href;
Or
var url = document.URL;
and I think Please use function name something different then split because it is a function of PHP and may be reason of problem.
thanks
I'm not exactly sure what yo are trying to do after you break the URL into parts but here is how you can get the current URL and put them into variables. You can put them back together however you like latter. Source: [http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/][1]
var urlNow = window.location.pathname.split('/');
var itNow0 = urlNow[0];
var itNow1 = urlNow[1];
var itNow2 = urlNow[2];
var itNow3 = urlNow[3];
alert(itNow0+ ' ' +itNow1+ ' ' +itNow2+ ' ' +itNow3);

jQuery/Javascript - reload current page with an appended querystring?

I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.
How would I go about doing this?
This is an old question but it came up first in google search results.
The solution I went with is similar to jAndy's.
window.location.pathname gives me the page's url without the query string.
I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.
window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
var params = [
"foo=bar",
"base=ball"
];
window.location.href =
"http://" +
window.location.host +
window.location.pathname +
'?' + params.join('&');
That code within your change event handler will do the trick.
For instance:
$('#my_dropdown_id').bind('change', function(){
var params = [
"foo=bar",
"base=" + $(this).val()
];
window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
If you go with the top rated answer, you may want to replace
http://
in the code with
window.location.protocol
so that it works for other protocols, like https or file. So
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
Actually, there a built-in function of location that you can use, the name of the function is assign.
For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.
So for your case you just need below example:
const url = new URL(location.href);
url.searchParams.set('key', 'value');
location.assign(url.search);
Update 2022
I create a TypeScript function to apply redirect with params more easier:
const isClient = (): boolean => typeof window !== 'undefined';
type ParamsType = { [key: string]: string | number };
const redirectUrl = (url: string, params?: ParamsType): void => {
if (isClient()) {
try {
const _url = new URL(url);
if (params) {
const keyList = Object.keys(params);
for (let i = 0; i < keyList.length; i += 1) {
const key = keyList[i];
_url.searchParams.set(keyList[i], params[key]?.toString());
}
}
window.location.assign(_url.href);
} catch (e) {
throw new Error('The URL is not valid');
}
}
};
export default redirectUrl;
If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:
var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo&param2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.
If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.
$("#sortby").change(function () {
var queryString = getQueryStrings();
// Add new params to the querystring dictionary
queryString["sortby"] = $("#sortby").val();
window.location.href =
window.location.protocol + "//" +
window.location.host +
window.location.pathname +
createQueryString(queryString);
});
// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
}
}
return assoc;
}
function createQueryString(queryDict) {
var queryStringBits = [];
for (var key in queryDict) {
if (queryDict.hasOwnProperty(key)) {
queryStringBits.push(key + "=" + queryDict[key]);
}
}
return queryStringBits.length > 0
? "?" + queryStringBits.join("&")
: "";
}
I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.
Using the code
window.location = window.location.pathname
+ window.location.search + '#tabs-4';
did'nt work for me but below code did.
location = "#tabs-4";
location.reload(true);

Categories