Hi i am new in javascript before i read the case split using the function. I just followed but not understand it. Can you guys give me a link or guide to explain how it work? tks a ton
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
This function return the value of each varrian from url.
In your code, you want to get id, page from url. I guest you have a url like : your-page?id=value&page=value, and you want to get them, don't you?
You need to read the replace function at http://www.w3schools.com/jsref/jsref_replace.asp
There is a kind of function you would like. Hope you will understand this :
var getUrlVars = function( url ){
if( !url.match( /\?/ ) ) return {};
var paramsfull = url.replace( /^.*\?/, "" ).split( /\&/g );
var params = {};
var _temp;
for( var p in paramsfull ){
_temp = paramsfull[ p ].split( /\=/ );
params[ _temp[ 0 ] ] = _temp[ 1 ];
}
return params;
}
var first = getUrlVars( window.location.href )[ "id" ];
var second = getUrlVars( window.location.href )[ "page" ];
Related
I get users redirected to my site with GET parameters like this:
www.example.com/?email=mail#mail.com&vorname=name1+name2
I use javascript to populate my texfields (newsletter subscription) like this:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
Like this it works properly but the parameter "vornametxt" contains plus signs if the GET parameter contains them. I want to replace the plus signs in the names with spaces which should work like this:
vornametxt = vornametxt.replace(/\+/g, " ");
That's what I found in older questions on stack overflow but it doesn't work.
What am I doing wrong? Is it possible that my wordpress site doesn't allow certain code?
I am using Wordpress and a plugin which allows me to add this javascript code to my sites footer.
Those values are URI-encoded with + meaning "space". To decode them, replace + with space and then use decodeURIComponent (to handle any other chars that have been encoded). I think it would go in your getUrlParam function, right at the end:
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
Live Example:
(function() {
var window = {
location: {
href: "http://www.example.com/&email=mail#mail.com&vorname=name1+name2"
}
};
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
})();
<input type="text" name="nn">
<br><input type="text" name="ne">
My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});
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
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;
});
I am (slowly) writing an XML parser for some "site definition" files that will drive a website. Many of the elements will be parsed in the same manner and I won't necessarily need to keep the values for each.
The XML
The parser so far
My question is actually pretty simple: How can I use jquery manipulators in an class function? How can I pass $(this)? I know that it sometimes refers to a DOM object and sometimes the jQuery object, but am a bit hazy.
For my function:
function parseXML(xml) {
$("book, site", xml).children().each(function() {
var label = $(this).get(0).tagName;
var text = $(this).text();
var key = toCamelCase(label);
if ((key in siteData) && (text != -1)){
if (isArray(siteData[key]))
{
$(this).children().each(function (){
var childLabel = $(this).get(0).tagName;
var childText = $(this).text();
var childKey = toCamelCase(childLabel);
if(isArray(siteData[key][childKey]))
{
siteData[key][childKey].push(childText);
}
else {
siteData[key].push(childText);
}
});
}
else
{
siteData[key] = text;
}
};
});
}
});
I want to place
var label = $(this).get(0).tagName; var text = $(this).text(); var key = toCamelCase(label);
in a class, so I can do something like
var child = new Element(); and var subchild = new Element();
and then use child.label , child.text and child.key...
But again, not sure how to use the jquery methods with these... I have more nodes to process and I don't want to keep doing stuff like var label = $(this).get(0).tagName; and then var childLabel = $(this).get(0).tagName;
Thanks.
var app = {};
app.element = function(data) {
return function() {
var _text = data.get(0).tagName, _label= data.text(), _key = toCamelCase(_label);
var that = {};
that.label = function() {
return _label;
}
that.text = function() {
return _text;
}
that.key = function() {
return _key;
}
return that;
}();
};
app.instanceA = app.element($(this));
document.writeln(app.instanceA.label());
Ok so this works but, I'm not sure if it's the best way.