I'm trying to create a javascript tracker that can be included on any page, that will pass the variables "ref" and "aff" from the URL to the PHP code that does the tracking.
This code works perfectly for my purposes on PHP pages:
<script type="text/javascript" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&aff=<?= $_GET['aff'] ?>">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&aff=<?= $_GET['aff'] ?>"/>
</div>
</noscript>
The issue is that I also need to add the tracker to non-PHP pages, so I need a pure Javascript solution to pass those URL parameters into src attributes.
[EDIT]
For anyone interested, here is the solution I ended up with:
<script type="text/javascript">
function fooParamParse(val) {
var result = '', tmp = [];
location.search.substr(1).split("&").forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = "//www.foo.com/reftracker.php?ref="+fooParamParse('ref')+"&aff="+fooParamParse('aff')+"";
</script>
You will need a pure javascript solution for that. Read here on how to read the GET parameters from url in javascript
Then add the follwing js code
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = "//www.foo.com/reftracker.php?ref="+GET['ref']+"&aff="+ GET['aff']+"";
// assuming the GET parameters from javascript are stored in a hash GET
Related
I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.
I an trying to grab url parameters onto a Zoho form in Squarespace for Google tracking purposes. I made a custom function to get the parameter and add it to a url. The alerts at the end are just to show that it is getting set correctly. But I am unable to add the form with the variable 'site'.
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com/....wj7Q?campaign="+campaign;
var scriptElement = document.createElement('script');
scriptElement.type = "text/javascript";
scriptElement.src = site;
scriptElement.id = "ZFScript";
document.head.appendChild(scriptElement);
alert(decodeURI(campaign));
alert(site);
alert(scriptElement.src);
alert(scriptElement.type);
alert(scriptElement.id);
</script>
So at the end I just need to run
<script type="text/javascript" src=site id="ZFScript"></script>
But I can not get it to write a new script with src equaling the site variable.
If you are using only javascript, you almost got it as #Julesezaar comment, I complement it with something like this:
document.getElementById('ZFScript').setAttribute('src',site);
And you are done.
I have a Zoho form embedded on a Squarespace site and I need to populate some fields with URL parameters in Javescript. I'm using the following code to get the parameters:
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
and then to set the parameters to variables:
var campaign1 = getUrlVars()["campaign"];
alert(campaign1);
So that gets the parameter named 'campaign' in the url and assigns it to 'campaign1'. The alert is just to show that it is working, and it is. Then I want to run this:
<script type="text/javascript" src="https://forms.zohopublic.com/....j7Q?campaign="+campaign1 id="ZFScript"> alert(campaign1); </script>
But no matter what I do I can't get that part to reference the variable in the 'src=' section, but I can reference it in the 'alert(campaign1);' immediately after.
I also tried this, which was meant to save the whole URL to a variable named 'site' and just run 'src=site', but that didn't work either.
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1
</script>
<script type="text/javascript"
src=site id="ZFScript"> alert(site);</script>
Your issue is that you are trying to write some js code where it is not parsed/rendered/executed.
The js code will be executed inside <script> tags or onEvent attributes. For instance onclick or onload.
So what you want to do is execute some js code inside a script tag that will generate a script tag with the dynamic src attribute you are trying to achieve. This is a way of doing it:
<script type="text/javascript">
// [...]
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1;
// create a script node
var scriptElement = document.createElement('script');
// set its src attribute
scriptElement.setAttribute('src', site);
// add you new script node to your document
document.body.appendChild(scriptElement);
</script>
I'm trying to make a javascript function to call another .js file like this:
scriptCaller.js
function callScript(file){
var script = document.createElement('script');
script.id = file;
script.type = 'text/javascript';
script.async = true;
script.src = "script/"+file+".js";
document.getElementById('scriptSection').appendChild(script);
}
Then I create some class to be called by that script in other file:
divGenerator.js
function divGenerator(){
var self = this;
var div = document.createElement('div');
this.tag = function(){
return div;
}
/*and some other function to style the div*/
}
Then i make the main file to be executed:
main.js
function build(){
callScript('divGenerator');
}
function main(){
var test = new divGenerator();
/*execute some function to style the div*/
document.getElementById('htmlSection').appendChild(script);
}
All the three file will be called in a HTML files that will execute the main function:
myPage.html
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
If I correct it should display the styled div, but what I got is an error that said:
TypeError: divGenerator is not a constructor[Learn More]
But, when I move the divGenerator() class to myPage.html it works fine. Any idea to solve this problem?
You need to add scriptCaller.js and divGenerator.js to your html script element.
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<script src="scriptCaller.js"></script>
<script src="divGenerator.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
You have couple of problems in your code. First of all, do not assign id to script element same as the "exported" global constructor name. You need to remember that anything with id attribute (and name) automatically gets exposed as global variable on window object. It means that divGenerator in your case is going to be reference to HTMLScriptElement, not a constructor function.
Second problem is related to timing, since you are loading script with async attribute. This is good, but you need to realise that in this case you can't expect that script will be loaded when you call main after build(). I would suggest to wrap script creation into promise:
function callScript(file){
return new Promise(function(resolve) {
var script = document.createElement('script');
script.id = 'script-' + file; // Note different id
script.async = true;
script.src = "script/" + file + ".js";
script.onload = resolve
document.getElementById('scriptSection').appendChild(script);
})
}
and use it like this:
<script>
build().then(function() {
main();
})
</script>
I have the below script and noscript javascript codes:
<script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5"> </script>
<noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5"
height="300" width="500" frameborder="0"></iframe>
<br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>
The above codes should be added to the page body only and only when a javascript variable is set from the server.
var shouldShow = true;
$document.ready(function() {
if (shouldShow) {
// add
} else {
// don't add
}
});
How would that possible to add those scripts at runtime?
Thanks,
You can use Page.RegisterStartupScript
if (shouldShow) {
Page.RegisterStartupScript...
}
You can do that like this:
var shouldShow = true;
$document.ready(function() {
if (shouldShow) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'https://www.google.com/recaptcha/api/challenge?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5';
document.body.appendChild(newScript);
} else { ... }
And you can freely ignore noscript. As it is shown only if there is no JS enabled, but in that case it will not be added anyway.
But why not simply place it into some asp:panel, for instance, and set its visibility to true/false depending on if it should be shown or not? If some asp.net element has elem.Visibility = false it is not sent to browser, the same as all its content.