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.
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);
I got an GET request on a webpage, with multidimensional checkboxes.
The GET request would look like this:
&company_state[AKERSHUS]=AKERSHUS&company_state[AKERSHUS][]=ASKER&company_state[SOGN+OG+FJORDANE]=SOGN+OG+FJORDANE&company_state[SOGN+OG+FJORDANE][]=ASKVOLL
As you can see, company_state is an array, wich again contains an array of values.
Is it possible to use jQuery or plain JS to grab the URL parameters, and trigger a click on the checkboxes with the same name (company_state, company_municipality) and value?
I tried using this, but this doesn't seem to work in this purpose to grab the params.
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
Thanks in advance.
EDIT:
Gives this result in console:
You can parse query string as array,
and then iterate over array and extract key and value.
Code is like this:
function getQueryParameters(str) {
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(
function(n){
return n = n.split("="),this[n[0]] = n[1],this;
}.bind({}))[0];
}
var url = "&company_state[AKERSHUS]=AKERSHUS&company_state[AKERSHUS[]=ASKER&company_state[SOGN+OG+FJORDANE]=SOGN+OG+FJORDANE&company_state[SOGN+OG+FJORDANE][]=ASKVOLL";
var arr = getQueryParameters(url);
for(var a in arr){
console.log("key:" , a.substr('company_state'.length), " value:" , arr[a]);
}
You have here a live example.
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];
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.
How can we collect a query string value in javascript.
my script is like follows
http://192.168.10.5/study/gs.js?id=200
here i want to collect the id value in my gs.js script file.
For this i am using
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
var string_value = getQuerystring('id');
alert(string_value);
But it is not getting..Please anybody can correct me.Please
This function gets the query string of the page hosting this script: it relies on window.location.href. It seems that http://192.168.10.5/study/gs.js?id=200 is the address of the script itself and not the page. In order to do this you will need to first obtain this address by looking at the script tags in your document and then slightly modify the previous function to take an additional parameter representing the url and not relying on window.location.href.
From my programming archive:
function querystring(key) {
var re = new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null) r[r.length] = m[1];
return r;
}
The function returns the found values as an array with zero or more strings.
Usage:
var values = querystring('id');
if (values.length > 0) {
// use values[0] to get the first (and usually only) value
// or loop through values[0] to values[values.length-1]
}
or:
var string_value = querystring('id').toString();