I'm hacking away at the react starter kit, and I came into a problem. I need javascript to get the query string from the url and display it in the document. I tried the following, but I get a location not defined. How can I do this in reacts and javascript?
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, " "));
}
#withStyles(styles)
class PlayerPage extends Component {
render() {
const title = 'Player';
var player = getParameterByName('player');
return (
<div className="PlayerPage">
<div className="PlayerPage-container">
<h1>{title}</h1>
<p>{player}</p>
</div>
</div>
);
}
}
The problem is that when your code runs in the server, location will not be defined because the node.js environment does not provide an implementation of location.
You may want to ensure that this component only renders on the client, or extract the route information from express request in server, rather than relying only on location.
Related
TL;DR: I am forced to use a javascript solution to store a URL parameter as a cookie, but when the function runs, it only stores the first 5 characters of the value I need.
I am working on implementing affiliate sales tracking across domains. As stated above, I need to store a value from a URL in a cookie so that I can pull it into a separate (functioning) script later. On my primary domain, I was able to do this with a simple .php script, but the third-party platform we use for our sales doesn't allow me to run .php scripts, so I found a javascript function that seemed to be working prior to today. That said, prior to today I was using test parameters that were only numerical (1234567890, etc.).
Here is an example of the kind of URL and parameter being used:
https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0
This is the function I've been using successfully up until now:
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, ' '));
}
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
For some reason, the function now only stores the first 5 characters of the value, or "QW6Qn" in this case. Any help or direction on how to make this work correctly is appreciated.
Resolution:
I found a function that was more apt for what I needed here on stackoverflow: How to get parameter name?, and replaced the first part of my javascript with the following, and it is now working as expected!
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, " "));
}
The last section remained the same:
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
Thank you to those that offered help and insight.
const url = new URL('https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0')
document.cookie = `irclickid=${url.searchParams.get('irclickid')}; expires=...`
You can see on https://caniuse.com/url if all required browsers support URL.
I'm using the JavaScript to create a cookie that will post the utm_source value="".
On the console I see the utm_source value, but not on the form
// Parse the URL
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, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
// Set the cookies
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
Cookies.set('utm_source', source);
}
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
});
</script>
Problem 1
$('input[name=utm_source').val(utm_source);
The above line is causing problems for two reasons:
You're missing a closing bracket
utm_source is not defined anywhere (in the snippet you posted)
If you want to use the cookie value, you should do this:
$('input[name=utm_source]').val(Cookies.get('utm_source'));
Problem 2
On this line:
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
I think that you're mistakenly using .set() instead of .get() and that it could be simplified into this:
if(!Cookies.get('utm_source')) {
which would work because null and "" are both falsy values.
Thank you guys! Got it to work! Had to replace the name=customID
I have deployed a firebase site which works fine. The problem I have is the next:
Inside my main.js I have a variable called company. Is there a way to set that variable depending on the URL? For example:
site-ce207.firebaseapp.com/company=01
Or do you know another way?
As Mouser pointed out, this is invalid:
site-ce207.firebaseapp.com/company=01
However, this isnt:
site-ce207.firebaseapp.com#company=01&id=5
And it can be easily parsed:
var queries=location.hash.slice(1).split("&").map(el=>el.split("="));
Queries now.looks like this:
[
["company","01"],
["id","5"]
]
So to resolve it may do use an object:
var getQuery={};
queries.forEach(query=>getQuery[query[0]]=query[1]);
So now its easy to get a certain key:
console.log(getQuery["company"]);
Or new and more easy using a Map:
var query=new Map(queries);
console.log(query.get("company"));
I have a simple function I found a long time ago to handle this. I modified a bit to get the value by doing this.
function param(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 to use the value I do the following
var myCity = param('cityid');
when issuing something like: http://example.com/?cityid=Guatemala
myCity will have the value of 'Guatemala' in my app.
Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!
I'm using the standard custom search installation. I have promotions setup to my account.
I have the following:
google.load('search', '1', { language: 'en', style: google.loader.themes.MINIMALIST });
google.setOnLoadCallback(function () {
var customSearchOptions = {};
customSearchOptions[google.search.Search.RESTRICT_EXTENDED_ARGS] = { 'as_sitesearch': '' };
var customSearchControl = new google.search.CustomSearchControl('CSE-UNIQUE-ID', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
customSearchControl.draw('cse', options);
customSearchControl.execute(getParameterByName("q"));
}, true);
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null) {
return "";
}
else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
I am setting the javascript object field: as_sitesearch via a CMS, so the code can be used across sites. When the field is populated with i.e ".example.com" the promotions do not display in the search results. They do on the other hand display in the auto-complete.
When the as_sitesearch field is empty the promotions display? Why is this?
Thanks
It appears that when a link for a promotion is linking to a sub-domain or another domain totally, the search filter removes the promotion from the results as its not within the given domain in the as_sitesearch field.
Although it appears the autocomplete search does not use the filter given and therefore displays the promotions.