Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.
Related
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
Get query string
var queryString = window.location.search;
removes ? from beginning of query string
queryString = queryString.substring(1);
query string processor
var parseQueryString = function( queryString ) {
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = queryString.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
// query string object
var pageParams = parseQueryString(queryString);
// CSS variables
var target = pageParams.target;
var prop = pageParams.prop;
var value = pageParams.value;
// can't get to work -->
jQuery(target).css({
prop : value,
});
I want to be able to supply a query like this one "?target=body&prop=display&value=none" and make the whole body disappear or target certain elements by their class.
You wouldn't be able to use prop as a key-variable for the object you're passing to .css(). In this case, it would translate to a literal string 'prop'. Instead, you'd have to do something like:
jQuery(target).css(prop,value);
Note: be careful about that trailing comma in that hash (after value). Some browsers will error at that point.
In order to create a css object which you can pass to jQuery, I suggest something like this:
// Create css obj
var cssObj = {};
cssObj[prop] = value;
After this, the code works fine to me. See the full solution here:
http://jsfiddle.net/q97DH/4/
I recommend removing the question mark with a regex - see comment below.
I have a page which uses dropdowns to filter a listing. I have over 10 filters now and each of the change function, I am calling an AJAX request and passing corresponding variables to the PHP function. Like this :
$("#categories").change(function() {
uri = "myurl" ;
var status=$("#statusfilter").val();
var category=$("#categories").val();
var network=$("#networksfilter").val();
var prod_type = $("#prodtypefilter").val();
loadData(uri,category,status,network,prod_type);
});
and in loadData() I have the following code :
function loadData(uri,category,status,network,prod_type){
url + = category+"/"+status+"/"+network+"/"+prod_type;
$('#userdata').load(url);
}
Here I have given only 4 filters only, but it is actually 10 and may increase.Anyway this is working fine. But the problem is that as I increase the filters, I need to write this same for every dropdown change function. Is there any better approach to optimze the code and so I don't need to load a bunch of JS ?
Rename your filter elements' IDs to start with same word, for example "filter_". Then get all of them at once:
$('select[id^="filter_"]').change(function() {
var uri = "myurl";
var filters = new Array();
$('select[id^="filter_"]').map(function () {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
loadData(uri,filters);
});
.map() iterates over its elements, invoking a function on each of them and recording the selected option value in the array.
You can use .each() if it's more intuitive from .map() for you:
$.each('select[id^="filter_"]', function() {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
Note: It's a good idea to use associative array as #Tony noticed below to be sure which filter is for which database table attribute in your server side script.
You will need to write some code in any cases, but you can reduce it, for example like this:
$("#categories").change(function() {
uri = "myurl";
var filters = {
status: $("#statusfilter").val(),
category: $("#categories").val(),
network: $("#networksfilter").val(),
prod_type: $("#prodtypefilter").val()
}; // order is important
loadData(filters );
});
loadData(filters) {
var url = '';
for (var filterName in filters)
url += '/' + (filters[filterName] || 'any'); // here some def value needed
url = url.substring(1); // cut first slash
$('#userdata').load(url);
}
EDIT
Or even like this:
loadData(filters) {
var url = Object.keys(filters).map(function(el) {
return filters[el] || 'any';
}).join('/');
$('#userdata').load(url);
}
I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.
I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];