I have seen lots of jQuery examples where parameter size and name are unknown.
My URL is only going to ever have 1 string:
http://example.com?sent=yes
I just want to detect:
Does sent exist?
Is it equal to "yes"?
Best solution here.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
Solution from 2023
We have: http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sent exist?
searchParams.has('sent') // true
Is it equal to "yes"?
let param = searchParams.get('sent')
and then just compare it.
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
I always stick this as one line. Now params has the vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
getSearchParams() //returns {key1:val1, key2:val2}
or
getSearchParams("key1") //returns val1
Yet another alternative function...
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
Using URLSearchParams:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));
Be careful about the compatibility (Mostly it's fine, but IE and Edge, may be different story, check this for compatible reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
May be its too late. But this method is very easy and simple
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet
Or you can use this neat little function, because why overcomplicated solutions?
function getQueryParam(param, defaultValue = undefined) {
location.search.substr(1)
.split("&")
.some(function(item) { // returns first occurence and stops
return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
})
return defaultValue
}
which looks even better when simplified and onelined:
tl;dr one-line solution
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result:
queryDict['sent'] // undefined or 'value'
But what if you have got encoded characters or multivalued keys?
You better see this answer: How can I get query string values in JavaScript?
Sneak peak
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
This one is simple and worked for me
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
so if your url is http://www.yoursite.com?city=4
try this
console.log($.urlParam('city'));
Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)
code:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
Minified version < 1kb
I hope this will help.
<script type="text/javascript">
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
$(window).load(function() {
var param = getParameters();
if (typeof param.sent !== "undefined") {
// Do something.
}
});
</script>
Try this working demo http://jsfiddle.net/xy7cX/
API:
inArray : http://api.jquery.com/jQuery.inArray/
This should help :)
code
var url = "http://myurl.com?sent=yes"
var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
This will give you a nice object to work with
function queryParameters () {
var result = {};
var params = window.location.search.split(/\?|\&/);
params.forEach( function(it) {
if (it) {
var param = it.split("=");
result[param[0]] = param[1];
}
});
return result;
}
And then;
if (queryParameters().sent === 'yes') { .....
This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
Example
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>
<span id="result"></span>
function GetRequestParam(param)
{
var res = null;
try{
var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
var ar = qs.split('&');
$.each(ar, function(a, b){
var kv = b.split('=');
if(param === kv[0]){
res = kv[1];
return false;//break loop
}
});
}catch(e){}
return res;
}
So simple you can use any url and get value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Usage Example
// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2"
Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).
There's this great library:
https://github.com/allmarkedup/purl
which allows you to do simply
url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
if (sent == 'yes') { // sent is equal to yes
// ...
}
}
The example is assuming you're using jQuery. You could also use it just as plain javascript, the syntax would then be a little different.
http://example.com?sent=yes
Best solution here.
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
With the function above, you can get individual parameter values:
getUrlParameter('sent');
This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://stackoverflow.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
There is another example with using URI.js library.
Example answers the questions exactly as asked.
var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';
// output results in readable form
// not required for production
if (sendExists) {
console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
if (urlParams.sent == 'yes') {
console.log('"Sent" param is equal to "yes"');
} else {
console.log('"Sent" param is not equal to "yes"');
}
} else {
console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
Coffeescript version of Sameer's answer
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++
A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling
var getURLParam = (function() {
var paramStr = decodeURIComponent(window.location.search).substring(1);
var paramSegs = paramStr.split('&');
var params = [];
for(var i = 0; i < paramSegs.length; i++) {
var paramSeg = paramSegs[i].split('=');
params[paramSeg[0]] = paramSeg[1];
}
console.log(params);
return function(key) {
return params[key];
}
})();
I use this and it works.
http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.
As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.
http://www.website.com/?error=userError&type=handwritten
var urlParams = location.search.substring(1).split('&'),
params = {};
urlParams.forEach(function(el){
var tmpArr = el.split('=');
params[tmpArr[0]] = tmpArr[1];
});
var error = params['error'];
var type = params['type'];
What if there is & in URL parameter like filename="p&g.html"&uid=66
In this case the 1st function will not work properly. So I modified the code
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:
-- Not depending on any outside libraries, including jQuery
-- Not polluting global function namespace, by extending 'String'
-- Not creating any global data and doing unnecessary processing after match found
-- Handling encoding issues, and accepting (assuming) non-encoded parameter name
-- Avoiding explicit for loops
String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};
Then you'd use it as:
var paramVal = "paramName".urlParamValue() // null if no match
If you want to find a specific parameter from a specific url:
function findParam(url, param){
var check = "" + param;
if(url.search(check )>=0){
return url.substring(url.search(check )).split('&')[0].split('=')[1];
}
}
var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";
alert(findParam(url,"order_no"));
Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
After that it's only a matter of using the parameters like this:
param.language
to return
en
The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
If your parameter contains numeric values then just parse the value.
parseInt(param.page)
If there are no parameters param will just be an empty object.
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
use this
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
I there a possible way to use a GET variable in jQuery url. Like in PHP we have something like this:
header('location : path/to/page.php?id='.$id);
And In the page.php we do this:
$id = $_GET['id'];
So in jQuery can we do something like:
window.location.replace(path/to/page.html/* and pass the url query here*/);
I think what you are looking for is to access the query string ($_GET in php) variables in javascript. You can use this function for that.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
and then call getParameterByName('id') to get ?id=val part of the current URL.
You can also pass data to another page using location.replace:
idVal = 1;
window.location.replace("path/to/page.php?id="+idVal);
Use a js function to do this...
var getUrlVars = function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == window.location.href){
vars =[];
}
return vars;
}
Then where ever you wish to use
var params = getUrlVars();
console.log(params["id"]);
console.log(params["whatever"]);
You can use it anywhere you want.
the property 'search' of the 'location' javascript object will give you the querystring parameters of the url, eg:
url: http://www.w3schools.com/submit.htm?email=someone#example.com
console.log(location.search);
// output: ?email=someone#example.com
after that you can parse it as you wish
I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp
Here is a part of my view(a javascript method that is executed on a button click):
function assign()
{
var links_list1 = [];
var links1 = document.getElementById('moderatorUsers').getElementsByTagName('a');
for(var a in links1) {
if(typeof links1[a] == undefined) continue;
links_list1.push(links1[a].innerHTML);} var str1 =links_list1.toString();
var moderators = str1.split(',');
var links_list2 = [];
var links2 = document.getElementById('editorUsers').getElementsByTagName('a');
for(var a in links2) {
if(typeof links2[a] == undefined) continue;
links_list2.push(links2[a].innerHTML);} var str2 =links_list2.toString();
var editors = str2.split(',');
var links_list3 = [];
var links3 = document.getElementById('jEditorUsers').getElementsByTagName('a');
for(var a in links3) {
if(typeof links3[a] == undefined) continue;
links_list3.push(links3[a].innerHTML);} var str3 =links_list3.toString();
var jEditors = str3.split(',');
}
Here is the controller method i need to call using the 3 arrays from the javascript(moderators, editors,jEditors):
function insertPos($moderators,$editors,$jEditors){
$account = new Account();
$account->insertPos($moderators,$editors,$jEditors);
}
I need to know how to execute the controller method insertPos($moderators,$editors,$jEditors) using the 3 arrays in the javascript method...
I used this to send the arrays in the javascript like you told me:
$.post('http://localhost/cakephp/Accounts/insertPos', {
data: {
'moderators': moderators,
'editors': editors,
'jEditors': jEditors
}
});
and in the controller i try to access my arrays like this:
public function insertPos() {
if (!empty($this->request->data)){
print_r($this->request->data);
$moderators = $this->request->data['moderators'];
$editors = $this->request->data['editors'];
$jEditors = $this->request->data['jEditors'];
$account = new Account();
$account->assignPos($moderators,$editors,$jEditors);
}
}
the part inside the if(!empty($this->request->data)) is never executed so that means the arrays have not been sent to the controller.... where is the problem?
thank you....
It looks like you're trying to access a controller class directly. This is not how CakePHP works. You have to go through the dispatch process. Please read: http://book.cakephp.org/2.0/en/getting-started/a-typical-cakephp-request.html
That said, the way you would POST to a CakePHP url is thusly:
// POST to the AccountsController's insertPos method
$.post('/accounts/insertPos');
To pass data, pass it in the data option as specified with jQuery, prefixed with 'data', like data[moderators] so it ends up in Cake's data variable.
$.post('/accounts/insertPos', {
data: {
'data[moderators]': moderators,
'data[editors]': editors,
'data[jEditors]': jEditors
}
});
The data will now end up in $this->request->data in Cake.
Looking at your insertPost() method, though, you are passing them simply as parameters, so instead you would write your ajax like so
// POST is unnecessary here, since you aren't POSTing data
$.get('/accounts/insertPos/'+moderators+'/'+editors+'/'+jEditors);
You will probably need to stringify your JavaScript arrays and use json_decode in your inserPos method to convert them to PHP objects, since you can't just pass arrays from JavaScript to PHP.
don't use array notation in data parameter; just use keys like this:
$.post('/accounts/insertPos', {
data: {
'moderators': moderators,
'editors': editors,
'jEditors': jEditors
}
});
and in your controller access it as $this->request->data[key] not $this->request->data->data[key]
in the view replace your assign function with the following:
var moderators, editors, jEditors;
function assign()
{
var links_list1 = [];
var links1 = document.getElementById('moderatorUsers').getElementsByTagName('a');
for(var a in links1) {
if(typeof links1[a] == undefined) continue;
links_list1.push(links1[a].innerHTML);} var str1 =links_list1.toString();
moderators = str1.split(',');
var links_list2 = [];
var links2 = document.getElementById('editorUsers').getElementsByTagName('a');
for(var a in links2) {
if(typeof links2[a] == undefined) continue;
links_list2.push(links2[a].innerHTML);} var str2 =links_list2.toString();
editors = str2.split(',');
var links_list3 = [];
var links3 = document.getElementById('jEditorUsers').getElementsByTagName('a');
for(var a in links3) {
if(typeof links3[a] == undefined) continue;
links_list3.push(links3[a].innerHTML);} var str3 =links_list3.toString();
jEditors = str3.split(',');
}
Good luck