I am trying to capture data from the google analytics cookie and have it populate hidden fields which will then send that information to my database in Silverpop. I have the UA code inserted on my webform, and via google analytics I can see that there is someone on the site(me). But I have tried several variations of javascript I have found on here to extract the campaign and source from the google cookie, and on form submit, have that information sent to my database. Any help would be greatly appreciated. Thank You
Okay, just gonna throw it out there that since GA uses first party cookies, you can use server-side code to parse the cookie. I don't know java well enough to give you that code, but the info is stored in the __utmz cookie and the value looks something like this:
21733335.1344455611.17.2.utmcsr=camp_source|utmccn=camp_name|utmcmd=camp_medium|utmctr=camp_term|utmcct=camp_content
The leading numbers and dots are a hash and visitor id and other stuff you don't really need to worry about, so you can just strip it. Then you can just explode at the pipe and will have an array of name=value pairs that you can further split at the equal sign.
I just mention this because it would be more efficient and tamper-proof to do it server-side. You don't need to even worry about passing it in a form; you can do it on the very first page view request.
But if you really want to do this with client-side code, or need some guidance about parsing the cookie, here is the javascript example:
<script type='text/javascript'>
// function to retrieve the GA campaign values
function getGACampaignCodes() {
var cv = {};
var utmz=document.cookie.match(/ __utmz=([^;]*)/);
if (utmz!=null&&typeof(utmz[1])!='undefined') {
utmz = utmz[1];
utmz = utmz.replace(/^[0-9.]+/,'').split('|');
for (var c=0,l=utmz.length;c<l;c++) {
var cn = utmz[c].split('=');
switch (cn[0]) {
case 'utmcsr' : cv.source=cn[1];
case 'utmccn' : cv.name=cn[1];
case 'utmcmd' : cv.medium=cn[1];
case 'utmctr' : cv.term=cn[1];
case 'utmcct' : cv.content=cn[1];
}
}
}
return cv;
}
// function to populate the hidden fields
function addGAToFormFields() {
var cv = getGACampaignCodes();
var f = document.forms['someForm'];
for (c in cv)
if (cv.hasOwnProperty(c))
f['ga['+c+']'].value = cv[c];
}
// call this when document is ready
addGAToFormFields();
</script>
</body>
</html>
Not sure what the java version would look like but this is an example of the posted vars in php:
Array
(
[ga] => Array
(
[source] => camp_source
[name] => camp_name
[medium] => camp_medium
[term] => camp_term
[content] => camp_content
)
)
Related
I'm trying to create a centralised list of ingredients that are brought into a warehouse. I know the Name, Volume & Cost of each of those ingredients and have detailed them in a master spreadsheet that will be updated with new ingredients and amended prices as time goes on.
I also have a bunch of recipes spreadsheets that use those ingredients. What I'd like to do is have those recipes spreadsheets reference the master spreadsheet to pull the cost value in the cell and volume value in the adjacent cell when the name of the ingredient is mentioned in plain English and then have those values updated when the master spreadsheet is amended.
function dataLookUp(item) {
var item = item.toLowerCase() // convert to lower case
.trim() // remove spaces at the start and at end
.replace(/ +/g, ' '); // replaces double spaces with single spaces
var ss = SpreadsheetApp.openById("Master Cost ID").getSheetByName("Cost");
var sheets = ss.getsheets();
var data = sheet.getDataRange().getValues();
function get_value(item) {
var texts = ['GNS#60'];
if (texts.includes(item)) return 0.64;
}
function get_volume(item) {
var texts = ['GNS#60'];
if (texts.includes(item)) return 1000; //in adjacent cell
}
}
I have tried a few methods and I'm struggling to get this off the ground. I'm trying to express what I want to do in garbage code, apologies if my code doesn't make sense. I don't particularly want to use IF because then every time I add a new ingredient, I'll have to change the script with hundreds of entries.
I'm at a bit of a loss where to go.
EDIT -
As requested, a sample spreadsheet here
Thanks for helping out with this code:
/**
* This fuction determines whether the ingredient is in the database & returns it's price point and breaks
* #constructor
* #customfunction
* */
function getCost(itemname){
const ss1 = SpreadsheetApp.getActive();
const ssh = ss1.getSheetByName('Cost');
let tf = ssh.getRange('A1:A'+ ssh.getLastRow()).createTextFinder(itemname).findNext();
return ssh.getRange(tf.getRow(),3).getValue();
}
function getVol(itemname){
const ss1 = SpreadsheetApp.getActive();
const ssh = ss1.getSheetByName('Cost');
let tf = ssh.getRange('A1:A'+ ssh.getLastRow()).createTextFinder(itemname).findNext();
return ssh.getRange(tf.getRow(),2).getValue();
}
This works great for a cost sheet that is in the same spreadsheet, but what I'm wanting to achieve is scraping values from an external spreadsheet (as in a different file) that is updated separately. This way if 20 recipes use the same ingredient and the price changes, I can just update the master cost spreadsheet instead of individually changing each file.
I'm running into a problem when trying to point the script towards an external spreadsheet via SpreadsheetApp.openById which pings an error:
Exception: You do not have permission to call SpreadsheetApp.openById. Required permissions: https://www.googleapis.com/auth/spreadsheets
I've read that .openById doesn't work anymore for what I'm trying to do. Is there another method to do this?
EDIT 2
I've added the Google Sheets API through services and I have created a custom menu item to trigger the permissions check needed to access the external spreadsheet, although it doesn't ping a permissions check and I'm still getting the same error as the previous edit. See what I've added:
`/**
* This function calls the database through a custom menu to give permission
*/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Database')
.addItem('Access', 'accessDB')
.addToUi();
}
function accessDB() {
SpreadsheetApp.openById('Database ID');
SpreadsheetApp.getUi().alert('Database now active!');
}`
Not quite sure what's going wrong here.
Return item cost
function getCost(itemname){
const ss1 = SpreadsheetApp.getActive();
const ssh = ss1.getSheetByName('Sheet1');
let tf = sh.createTextFinder(itemname).findNext();
return ssh.getRange(tf.getRow(),3).getValue();
}
or
function getCost(itemname){
const ss1 = SpreadsheetApp.getActive();
const ssh = ss1.getSheetByName('Sheet1');
let tf = sh.getRange('A1:A'+ ssh.getLastRow()).createTextFinder(itemname).findNext();
return ssh.getRange(tf.getRow(),3).getValue();
}
Try this:
Since now you are getting a permission error when opening the external script you could try the following:
Try adding the specific scopes in the appscript.json file manifest, to do this follow this documentation.
If the above still throws the same message find your project and remove all access from your account settings, once done try giving permissions to the script again when running the code.
I'm currently working on an application built in Scala with Spray routing.
So for dealing with a JSON document sent over POST, it's pretty easy to access the variables within the body, as follows;
respondWithMediaType(`application/json`) {
entity(as[String]) { body =>
val msg = (parse(body) \ "msg").extract[String]
val url = (parse(body) \ "url").extractOpt[String]
However, I'm now trying to write an additional query with GET, and am having some issues accessing the parameters sent through with the query.
So, I'm opening with;
get {
respondWithMediaType(`application/json`) {
parameterSeq { params =>
var paramsList = params.toList
So, this works well enough in that I can access the GET params in a sequential order (just by accessing the index) - the problem is, unfortunately I don't think we can expect GET params to always be sent in the correct order.
The list itself prints out in the following format;
List((msg,this is a link to google), (url,http://google.com), (userid,13))
Is there any simple way to access these params? For example, something along the lines of;
var message = paramsList['msg']
println(message) //returns "this is a link to google"
Or am I going about this completely wrong?
Apologies if this is a stupid question - I've only switched over to Scala very recently, and am still getting both acquainted with that, and re-acquainted with Java.
What I usually do is use the parameters directive to parse the data out to a case class which contains all the relevant data:
case class MyParams(msg: String, url: String, userId: Int)
parameters(
"msg".as[String],
"url".as[String],
"userId".as[Int]
).as[MyParams] {
myParams =>
// Here you have the case class containing all the data, already parsed.
}
To build your routes you could use the parameters directives. I'm not sure if this is what you're looking for, anyway you could use them as:
get {
parameters('msg) { (msg) =>
complete(s"The message is '$msg'")
}
}
Spray directives can be easily composed so you can use combine them in any way you want.
I hope that helps you.
I have found other question regarding on this, but still im having a problem,When i check getParamerterValues, its always return null, and i think im having trouble redirecting it to my controller.Bare with me, in new to web app.
arr = [];
$(document).on("click","#idhere",function(){
$.post("servlet.html","ids="+arr+"",function(response){
});
});
or is there something like converting array of javascript to JSON of array in JSP so i can pass it to my servlet?
String arr [] = request.getParameterValues("ids");
if(arr != null){//this line doesnt return true even my array contains item}
change
String arr [] = request.getParameterValues("arr");
to
String arr [] = request.getParameterValues("ids");
Its always return null, and i think im having trouble redirecting it to my controller
I couldnt see any code to pass the values to the controller. In your jquery function , you have something like this $.post("servlet.html","ids="+arr+"",function(response){
It is not possible to post a value to the other html file from jsp. if you are trying to pass the values to the servlet.
try something like this ,
$(document).on("click","#idhere",function(){
$.post("servletName","ids="+arr+"",function(response){
});
});
Note: servletName refers to the url , mapped in your web.xml for the servlet you are trying to post the data.
Also make sure you jquery function is posting the data correctly to the controller through the browser console .
As the examples below show, the post method wants an json object as the data parameter.
This should do the job
$.post("servlet.html",{"ids": arr.join()},function(response){
});
Examples: Example: Request the test.php page, but ignore the return
results.
1 $.post( "test.php" ); Example: Request the test.php page and send
some additional data along (while still ignoring the return results).
1 $.post( "test.php", { name: "John", time: "2pm" } ); Example: Pass
arrays of data to the server (while still ignoring the return
results).
1 $.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } ); Example:
Send form data using ajax requests
1 $.post( "test.php", $( "#testform" ).serialize() );
see http://api.jquery.com/jquery.post/
basically my problem is when I want to mix javascript with java code since I did not take the variable (var nombreRodamiento javascript) when I put the "<%" to start putting java code.
please note the bold line, which is what the compiler does not like.
<script type="text/javaScript">
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {//izquierda
if (listLeft.options.length == 0) {
alert('Ya aprobaste todos los items');
return false;
} else {
var rodamientoElegido = listLeft.options.selectedIndex;
var nombreRodamiento = listLeft.options[rodamientoElegido].text;
move(listRight, listLeft.options[rodamientoElegido].value,
listLeft.options[rodamientoElegido].text);
listLeft.remove(rodamientoElegido);
<%
**String nombreRodamiento = '%> nombreRodamiento;<%'**
for (int i=0;i<listaItems.size();i++){
if (listaItems.get(i).equals(nombreRodamiento))
listaItems.remove(i);
}
%>
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
}
}
</script>
Regards
Assuming that this is all inside of a JSP. The java code (scriptlet, everything inside the <% %> tags) will execute server side, and the javascript will execute client side (in the user's browser). Yet you seem to be assigning a java variable the value of a javascript variable, nombreRodamiento. That is not going to work. The javascript is just text, with no values, execution context, etc, whenever the scriplet is being evaluated.
Java strings require double quotes, and you're missing a semicolon, which Java will not automatically insert.
Assuming this is a part of jsp file java code and js code executes separately. first java code get execute on server side and then the javascript code and that is on client side. Infact the java scriplet in jsp renderes the js code to be executed later on client which in this case is a browser.
Hence one cannot assign javascript variable value to a java variable but the reverse is possible.T
Edit:
I can give you the steps as I dont know your server side implementation.
render the page. You must be rendering the list by some type of array or equivaletn object on server side. save both right and left side element on session.
when the list box do some element exchange. exucute your js code.
you have to update the same on server side so send the selected element index and side information to server side using ajax.
update the server side list objects in the session accordingly. Update db if needed.
From next time render this list box suing this objects on ths server side sessions.
Hope this helps.
After many years of successfully maintaining an applet that uses the good old:
<script src="foo.js"></script>
method of embedding a Java applet, we're unable to cover our ears and sing "La la la!" anymore.
It's time to be using:
deployJava.runApplet()
When I fire this method using a click handler (here using an event listener on a button via jQuery, but it doesn't matter):
$('#button').click(function() {
deployJava.runApplet(attributes, parameters, version);
});
...it wipes out the entire existing document and replaces it with the applet. All I need to know is how to target a specific DOM element to be the container for the applet, so that my page doesn't get wiped.
It seems like it would be an attribute I could pass in the form of target: someElement where "someElement" is either a DOM object or the element's ID as a string. But alas, I can't find documentation for such an attribute.
For the sake of being complete, here's what's being passed:
/*here is where I imagine there might be an applicable attribute */
var attributes = {
name: "SomeName",
code: "some.class",
archive: "some.jar",
width: 640,
height: 400
};
var parameters = {
someParameter: someValue
};
var version = "1.5";
I can document.write everything I need to rebuild a document, but I'm sure you can all well imagine how hideous that prospect seems to me.
Any pointers would be greatly appreciated.
As alternative to Christophe Roussy solution you may override document.write while running deployJava.runApplet.
Like so:
function docWriteWrapper(func) {
var writeTo = document.createElement('del'),
oldwrite = document.write,
content = '';
writeTo.id = "me";
document.write = function(text) {
content += text;
}
func();
writeTo.innerHTML += content;
document.write = oldwrite;
document.body.appendChild(writeTo);
}
An then:
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, "1.6");
});
A little bit hackish but works like a charm;)
So the core of the problem is this: deployJava.js uses document.write. If you use this method AFTER page render (vs. as a part of the initial page render) it will first clear the document. Which has obvious negative repurcussions.
Although intended for JavaFX, people have reported success with dtjava.js, and I have every reason to believe it's a viable alternative.
However, other stakeholders on my team have already done work surrounding deployJava.js and are unwilling to throw away that work, which meant I needed to stick to deployJava.js. There's only one way to do this: make sure that deployJava is called during page render, not via Ajax, event, or other delayed trigger.
In the end, we are collecting our information, and passing it to a second page which will render the applet as expected. It works, and in most scenarios our clients will be doing this anyhow (collecting information, passing it server-side, and getting a redirect response), so it didn't make sense to force the issue. We are passing information via query string but you could probably use cookies and/or localstorage API instead, if you wanted the window.location to stay cleaner-looking.
Thanks for the replies, even though they were in the comment area. Other replies are still being taken on board if someone has a better way of doing it!
If you are using jQuery and want to target a specific dom element, rather than just appending:
function docWriteWrapper(jq, func) {
var oldwrite = document.write, content = '';
document.write = function(text) {
content += text;
}
func();
document.write = oldwrite;
jq.html(content);
}
docWriteWrapper($('#mydiv'), function () {
deployJava.runApplet(attributes, parameters, version);
});
To solve this annoying issue I downloaded and hacked deployJava.js at line 316, replaced the line by my own:
// document.write(n + "\n" + p + "\n" + r);
myDiv.append(n + "\n" + p + "\n" + r);
Where myDiv is a js global variable set to the desired div before calling runApplet:
myDiv = jQuery('#someDiv');
If you find a less intrusive solution let me know...