Ok, I'm new to JavaScript and need some help here. Working on forward/backward buttons on a page. Essentially, the url looks like this http://webaddress.com/details?id=27
So, my two functions are meant to extract the url and forward to the same page decrementing or incrementing the details id as necessary when one of the buttons is clicked. For example when someone clicks on the next button, id=28 is shown; and if previous is clicked, id=26 is shown.
I think it's something like substring, I've seen it done somewhere before, but not sure how's done.
I need idea on how to approach it.
Any help will be appreciated.
Update: I was using #gion_13's code below, but looks like I'm missin something. It doesn't seem to work. Any other help will be appreciated.
You can use location.href to get or set the URL.
http://developer.mozilla.org/en/window.location
Use exec to extract the identifier.
extracted_id = /id=([0-9]+)$/.exec(location.href)[1]
http://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec
Read the url as var url = document.location.href
Use regEx or indexOf "=" or document.location.search to find current page no
Parse as int and +/- page number
rebuild the the url
document.location.replace(newurl)
function parseUrl(){
if(location.href.indexOf('?') == -1)
return null;
var aux = location.href.split('?');
var result = {
'href' : aux[0],
'params' : {}
};
var p = aux[1].split('&');
for(var i=0,l=p.length;i++)
{
var kv = p[i].split('=');
params[kv[0]] = kv[1];
}
return result;
}
function reconstructUrl(obj){
if(!obj)
return location;
var url = obj.href + '?';
for(var i in obj.params)
url += i + '=' + obj.params[i] + '&';
return encodeURI(url);
}
function getNextUrl(){
var urlObj = parseUrl();
urlObj.id++;
return reconstructUrl(urlObj);
}
function getPrevUrl(){
var urlObj = parseUrl();
urlObj.id--;
return reconstructUrl(urlObj);
}
The window.location object has the URL info you need. You can parse it using a regex. Here's some references:
https://developer.mozilla.org/en/window.location
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
To access the URL of the page, use document.URL, for example:
document.write(document.URL);
You can then modify the URL and open the new URL.
For lots of hints and tips, See JavaScript HTML DOM Examples.
You can do that without Javascript if you want. I think it's more efficient with PHP, because it will work even if some user has Javascript disabled.
You can try get the id like this:
<?php $my_id = $_GET['id']; ?>
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 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);
}
So I've seen lots of scripts to grab the YouTube ID from a URL with JavaScript, but I can't find or figure out how to grab the ID along with any additional variables. I have a PHP script which can do it, but I'd like to do this with JavaScript. Does anyone know how this can be accomplished?
I doubt it's necessary but here are the two scripts I'm using
JavaScript for video ID...
url = $(this).text();
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
alert(match[2]);
}else{
alert("not youtube");
}
And PHP...
if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$youtubeid = $match[1];
$getyt = (parse_url($url));
}
if(strlen($getyt['fragment']) > 0) {
$addhash = '#' . $getyt['fragment'];
}
$embed = "http://www.youtube.com/embed/$youtubeid?wmode=opaque&autoplay=1$addhash";
The PHP one is pretty good, except that it only works for hash tags. My primary reason for wanting the additional variables is for when someone wants to specify a start time. So if anyone can tell me how I can grab the URL and additional paramaters (or just the specified starting time of the video) then I'd really appreciate it, because I'm absolutely lost.
This creates an associative array named video_parameters:
function extractParameters(url)
{
var query = url.match(/.*\?(.*)/)[1];
var assignments = query.split("&")
var pair, parameters = {};
for (var ii = 0; ii < assignments.length; ii++)
{
pair = assignments[ii].split("=");
parameters[pair[0]] = pair[1];
}
return parameters;
}
url = "http://www.youtube.com/watch?v=gkU&list=UUa3Q&feature=plcp";
video_parameters = extractParameters(url);
// video_parameters["v"]
// > "gkU"
// video_parameters["list"]
// > "UUa3Q"
See How can I get query string values in JavaScript? for methods that handle special chars.
Given a string containing an absolute URL with a querystring parameter, what is the easiest way to replace the value of the parameter using JavaScript and/or MooTools?
e.g.
// Change this
'/foo/bar?frob=123456789'
// Into this
'/foo/bar?frob=abcdefg'
EDIT
The URL is not the location of the current window. It is a variable containing a string. I just want to manipulate this string.
Further to what you did, this may be better as it will extend String and it removes dependency on URI class...
(function() {
// deps on Types/String.toQueryString()
String.implement({
fixQueryString: function(key, value) {
var query = this.parseQueryString() || {};
query[key] = value;
return Object.toQueryString(query);
}
});
// exports:
this.replaceUrlParameter = function(url, key, value) {
var parts = url.split('?'), QS = parts[1] || null;
return QS ? [parts[0], QS.fixQueryString(key, value)].join("?") : url;
};
})();
console.log(replaceUrlParameter('/foo/bar', 'frob', 'ownies'));
/foo/bar/
console.log(replaceUrlParameter('/foo/bar?frob=123123123', 'frob', 'ownies'));
/foo/bar?frob=ownies
http://jsfiddle.net/dimitar/fjj6W/
Sorry for bumping an old post but I think it's already in mootools. No need to write it yourself :-) http://mootools.net/docs/more/Types/URI#URI:setData
Or take a look here if your on a very old version of mootools: http://pilon.nl/mootools/2009/02/05/extra-browsersextras/
If You want to do this without reloading the page, there is no way (this is part of the web browser security model).
If You don't mind reloading the page, consider:
location.href='http://example.com/foo/bar?frob=baz'
An alternative without reloading is using location.hash, i.e.
location.hash = 'myhash'
to change url to http://example.com/foo/bar?frob=123456789#myhash
This is the basis of the Hash bang urls
This is the solution I came up with. This is dependent on MooTools.
function replaceUrlParameter (url, parameterName, newValue) {
var uri = new URI(url);
var uriBase = ri.get('directory') + uri.get('file');
var query = uri.get('query').parseQueryString(false, true);
query[parameterName] = newValue;
uriBase += '?';
for (var i in query) {
if (i === 'undefined') continue;
if (i === '') continue;
uriBase += i + '=' + escape(query[i]) + '&';
}
return uriBase.substring(0, galleryLinkBase.length - 1);
}
This is specific to my usage but it might serve as a starting point for others in the future.
Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks
You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.
I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}