Getting URL data with JavaScript (split it like php $_GET) - javascript

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}

If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

Related

How to pass Decoded Parameter in document.createElement("input") JavaScript

The Below code passes required parameter to value but send URI encoded parameters like Page=2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX but howto send decoded parameter value like Page=2&range=0.00Mb TO 14.00Mb&file_type=DOC&file_type=DOCX
var para_wotext="";
var com_para=location.search.substring(1).split("&");
$.each(com_para, function( index, value ) {
if(((value.indexOf("cores")) < 0) && ((value.indexOf("textSearch")) < 0) )
{
para_wotext+="&"+value;
}
});
console.log("para_wotext"+para_wotext);
prints in console as :
2&range=NONE&file_type=PDF&file_type=XLS which is correct
if(!document.getElementById("search-form").Page)
{
var hidden = document.createElement("input");
console.log(hidden);
hidden.type = "hidden";
hidden.name = "Page";
hidden.value = pageNum+decodeURIComponent(para_wotext).toString();//passing decoded parameter
var f = document.getElementById("search-form");
f.appendChild(hidden);
console.log(f);
}
f.submit()
but by Calling f.submit() the submitted form gets prameters as Page=2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX
if you want to decode Data then use this one where Page is your data
var Page ='2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX';
var uri_dec = decodeURIComponent(Page);

Set body class based on url with params

Im trying to set a body class based on the url - I can get it to work with a plain /Tablet/ url, like the code below.
But I need to set it to a url that has params in it, and I can't get that to work. How do I do it with this url?
/Tablets/?param=grid&pld0page=1&spcs=1
Script:
$(function() {
var loc = window.location.href; // returns the full URL
if(/Tablets/.test(loc)) {
$('body').addClass('test');
}
});
If, as you have mentioned in comments, the query parameter order is important, you can use this...
var url = location.pathname + location.search
console.info(url)
$(document.body).toggleClass('test',
url === '/Tablets/?param=grid&pld0page=1&spcs=1')
This lets you omit the URL scheme, host and port parts, focusing only on the path and query parameters.
You just have to search for text you want in the url string. You are doing fine in the code above. Just change
$(function() {
var loc = window.location.href; // returns the full URL
if(loc.includes('Tablets')) { // will return true/false
$('body').addClass('test');
}
});
Read on includes or here. You can do the same for other tests too, if you are checking for other strings in url. Hope this helps.
You can use this
$(function() {
var url = window.location.href;
url = url.replace(/^.*\/\/[^\/]+/, '')
if(url == '/Tablets?param=grid&pld0page=1&spcs=1') {
$('body').addClass('test');
}
});
If your URL is "http://www.google.com/?param=grid&pld0page=1&spcs=1", then the above queryString variable would be equal to "?param=grid&pld0page=1&spcs=1".
You can check the string is not empty
Replace your code with this
var loc = window.location.href; // returns the full URL
var url = loc.split( '/' );
var chunk = url[ url.length - 2 ];
if(loc.indexOf(chunk) >= 0) {
$('body').addClass('test');
}
var loc = 'http://localhost/Tablets/?param=grid&pld0page=1&spcs=35';
var patt = new RegExp("/Tablets/");
if(patt.test(loc) && loc.split('?').length > 1)
{
console.log('true');
$('body').addClass('test');
}
else
{
console.log('false');
$('body').removeClass('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Fetching Data from URL in Meteor

I'm trying to pass data through a URL in meteor. When I console.log the object it is empty, however, when i refresh the page, the object is displayed correctly in console.log.
I have a button in a google maps infoWindow which has an href to the page and with the parameters i want to pass over.
Js.
var infowindow = new google.maps.InfoWindow({
content: '<div id="infowin"><p>'+name+'"s storage </p>' +
'Space: '+space+
'<p>Price: '+price+'<div>Request Storage</div>' +
});
In the template i try to access this data :
Js.
Template.storageRequest.onCreated(function () {
// Use this.subscribe inside onCreated callback
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
Template.storageRequest.requestData = GET;
});
Any help is appreciated

jQuery redirect to source url

I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});

Find out relative urls in javascript

I want to know if the url is relative or no using javascript. Basically i will be passed the url, if the url is relative append the current url i.e minus the file name. Can some one help me with this
eg:-
CURRENT URL = http://example.com/big/index.html
PASSED URL 1 = newindex.html
OUTPUT = http://example.com/big/newindex.html
PASSED URL 2 = http://mysite.com/big/newindex.html
OUTPUT = http://mysite.com/big/newindex.html
So the simplest would be something like
var loc = location.href;
var dir = loc.substring(0,loc.lastIndexOf('/'));
function getHref(urlString) {
if (urlString) return (urlString.toLowerCase().indexOf('http:')==0)?urlString:dir+'/'+((urlString.indexOf('/')==0)?urlString.substring(1):urlString);
}
I am using the location object, substring, indexOflink text, lastIndexOf and the ternary operator - nested
<script type="text/javascript">
var loc = location.href;
var baseurl = loc.substring(0,loc.lastIndexOf('/'));
function getoutputurl(inputurl)
{
var returnurl = '';
if (inputurl)
{
if(inputurl.toLowerCase().indexOf('http://')==0)
{
returnurl = inputurl;
}
else
{
returnurl = baseurl+'/' ;
if(inputurl.indexOf('/')==0)
{
returnurl = returnurl + inputurl.substring(1);
}
else
{
returnurl = returnurl + inputurl;
}
}
}
return returnurl;
}
alert(getoutputurl('http://google.com'));
alert(getoutputurl('google.com'));
</script>
Try out this code it works
Use regular expresion to check if passed url have non relative component. If not create new output url based on part of current url ( cuted via regular exp also for example) and relative part.

Categories

Resources