I need to pass back a unique ID in place of "INSERT+ORDER+ID" for when a user clicks on our "Request Information" button to better track our visitors. Does anyone know how I can accomplish this? Any help would be much appreciated, thanks!
<script type="text/javascript">
var _qevents = _qevents || [];
(function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") +
".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scpt = document.getElementsByTagName('script')[0];
scpt.parentNode.insertBefore(elem, scpt);
})();
_qevents.push(
{qacct:"p-yeADJca0S9FXE",labels:"_fp.event.Request Information Confirmation
Page",orderid:"INSERT+ORDER+ID"}
);
</script>
<noscript>
<img src="//pixel.quantserve.com/pixel
/p-yeADJca0S9FXE.gif?labels=_fp.event.Request+Information+Confirmation+Page&
orderid=INSERT+ORDER+ID" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/>
</noscript>
assuming you mean a random unique ID,
for the javascript event tracking this should work:
// function to generate random id in js
function getRandomId() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
var btnReqInfo = document.getElementById('request_information_btn');
// bind the click on button
btnReqInfo.addEventListener('click', function() {
// track the event
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage",orderid: getRandomId() });
, false);
About the content in the noscript tag, you can't do it with static html of course so you have to put in the context of your template (in the php file), something like this that generates a unique ID and then echo it in place of your placeholder.
Since I'm in the mood for structuring and cleaning, I took the liberty of refactoring a bit the code, in case, you can replace all your script with this (assuming you're using plain js (vanilla) and html 5):
<script>
var _qevents = _qevents || [];
(function() {
var
init = function() {
loadScript();
bindUi();
},
loadScript = function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scrpt = document.getElementsByTagName('script')[0];
scrpt.parentNode.insertBefore(elem, scrpt);
},
bindUi = function() {
var btnReqInfo = document.getElementById('request_information_btn');
btnReqInfo.addEventListener('click', track.order, false);
},
track = {
order: function() {
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage", orderid: utils.getRandomId() });
}
},
utils = {
getRandomId : function() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
};
init();
})();
</script>
I would suggest using an AJAX call that is binded to the onclick event or .click if you're using JQuery
The AJAX call would hit a PHP script or call whatever you're using for analytics.
Related
I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>
I have added a random post button to my site (http://factowy.blogspot.com). I want to load random post as the page loads instead of clicking the button. How can I do that? Here is the code for the random post button.
<script type="text/javascript">
function showLucky(root){ var feed = root.feed; var entries = feed.entry || []; var entry = feed.entry[0]; for (var j = 0; j < entry.link.length; ++j){if (entry.link[j].rel == 'alternate'){window.location = entry.link[j].href;}}} function fetchLuck(luck){ script = document.createElement('script'); script.src = '/feeds/posts/summary?start-index='+luck+'&max-results=1&alt=json-in-script&callback=showLucky'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); } function feelingLucky(root){ var feed = root.feed; var total = parseInt(feed.openSearch$totalResults.$t,10); var luckyNumber = Math.floor(Math.random()*total);luckyNumber++; a = document.createElement('a'); a.href = '#random'; a.rel = luckyNumber; a.onclick = function(){fetchLuck(this.rel);}; a.innerHTML = 'Random Fact'; document.getElementById('abt-random').appendChild(a); } </script><script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
You need something like this.
<body onload='showLucky()'>
Go to Blogger > Layout > Edit HTML and replace <body> with above mentioned code and check.
It's just way you would call function on page load. I haven't tried with your function.
I was able to load random post with the following code:
window.onload = function(){fetchLuck(a.rel);}
I trying to create iframe then add script to it and script will run. Iframe created, but it always get errors in process of appending script to that iframe. Please help.
<div align="center" id="adframe1">
<script type="text/javascript">
var response1 = '<script>var ad_unit="123";</scr'+'ipt><script src="http://abc.com/abc.js"></scr'+'ipt>';
$('<iframe id="adframe1mopub"/>').appendTo('#adframe1');
$('#adframe1mopub').ready(function() {
$('#adframe1mopub').contents().find('body').append(response1);
});
</script>
</div>
You can try this script:
HTML:
<div id=container-iframe></div>
JS:
var response1 = '<script>var ad_unit="123";</scr' + 'ipt><script src="http://abc.com/abc.js"></scr' + 'ipt>';
$('<iframe></iframe>', { id: 'adframe1mopub' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
this.contentWindow.document.body.innerHTML += response1;
}).appendTo('#container-iframe');
But it would be best way to implement this:
$('<iframe></iframe>', { id: 'myiframe' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
var scripWidthCode = document.createElement('script');
scripWidthCode.type ='text/javascript';
scripWidthCode.innerText = 'var ad_unit="123";';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthCode);
var scripWidthSrc = document.createElement('script');
scripWidthSrc.type ='text/javascript';
scripWidthSrc.src = 'http://abc.com/abc.js';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthSrc);
}).appendTo('#container-iframe');
test
I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)
I'm developing in javascript and would like to insert a script only if a condition is verified.
For example:
var a = exampleVariable;
if (a == conditionIwant) {
// append to head:
<script src="http://code.jquery.com/jquery-1.5.js"> </ script>
}; //or something like this
How can I insert jquery.js only if a condition is true?
This is really simple:
if(somethingIsTrue) {
var sc = document.createElement('script');
sc.src = 'http://code.jquery.com/jquery-1.5.js';
sc.type = 'text/javascript';
if(typeof sc['async'] !== 'undefined') {
sc.async = true;
}
document.getElementsByTagName('head')[0].appendChild(sc);
}