How can I force the __utmz cookie to be set on the first page load - cookies

I am using a sweet little function to track visitors to my site and dump the info to Salesforce. However many form submissions have (none) set for many values because (as I understand it) the cookie is not set until the second page load.
I have tested this and that seems to be accurate, the problem is many people fill out a form on the first page, and I don't get any info through these submissions.
I am loading GA as follows:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29066630-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
And then running a php function to parse the __utmz cookie apart:
function tracking_cookie() { // ver 1.5
$trackarr = split('[|]',$_COOKIE["__utmz"]);
$conversion = $_COOKIE["Conversion"];
for($i=0;$i<count($trackarr);$i++){
$keyvalues=split('[=]',$trackarr[$i]);
$key=substr($keyvalues[0],-6);
switch ($key){
case "utmcsr":
$cookie['SearchEngine'] = $keyvalues[1];break;
case "utmccn":
$cookie['SearchCampaign'] = $keyvalues[1];break;
case "utmcmd":
$cookie['SearchType'] = $keyvalues[1];break;
case "utmcct":
$cookie['AdText'] = $keyvalues[1];break;
case "utmctr":
$cookie['Keyword'] = $keyvalues[1];break;
case "mgclid":
$cookie['isPPC'] = $keyvalues[1];break;
}
}
I have more code running after this. Any ideas on how to force the cookie to load the first time around?

A cookie isn't readable until the second page load - because they get sent in the request.
What you could do is on the initial page load (and no _utmz cookie is found in PHP) append another JS file / invoke some JS that will run an ajax command back to your server after the page has loaded.
This will act as the second page load and should have access to the new cookie (and the user wouldn't have left the page)

Have you taken a look at this Force.com Toolkit for Google Analytics? May be more reliable to get the information right from Google. Without knowing what else you are tracking or how you are storing it in Salesforce it is hard to give more detail.
https://github.com/mavens/Force.com-Toolkit-for-Google-Analytics
There is also some discussion on Google Groups - http://groups.google.com/a/googleproductforums.com/forum/#!category-topic/analytics/discuss-tracking-and-implementation-issues/bVR84di07pQ
You did say, "Many form submissions have none", so does that mean you do get data from time to time? Can you narrow it down to a browser?

Related

Adding a cookie to DocumentRequest

Using AngleSharp v 0.9.9, I'm loading a page with OpenAsync which sets a bunch of cookies, something like:
var configuration = Configuration.Default.WithHttpClientRequester().WithCookies();
var currentContext = BrowsingContext.New(configuration);
// ....
var doc = context.OpenAsync(url, token);
This works fine and I can see the cookies have been set. For example, I can do this:
var cookieProvider = currentContext.Configuration.Services.OfType<ICookieProvider>().First() as MemoryCookieProvider;
And examine it in the debugger and see the cookies in there (for domain=.share.state.nm.us)
Then I need to submit a post:
var request = new DocumentRequest(postUrl);
request.Method = HttpMethod.Post;
request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
request.Headers["User-Agent"] = userAgent;
//...
Which eventually gets submitted:
var download = loader.DownloadAsync(request);
And I can see (using Fiddler) that it's submitting the cookies from the cookieProvider.
However, I need to add a cookie (and possible change the value in another) and no matter what I try, it doesn't seem to include it. For example, I do this:
cookieProvider.Container.Add(new System.Net.Cookie()
{
Domain = ".share.state.nm.us",
Name = "psback",
Value = "somevalue",
Path = "/"
});
And again I can examine the cookieProvider in the debugger and see the cookie I set. But when I actually submit the request and look in fiddler, the new cookie isn't included.
This seems like it should be really simple, what is the correct way to set a new cookie and have it included in subsequent requests?
I think there are two potential ways to solve this.
either use document.Cookie for setting a new cookie (would require an active document that already is at the desired domain) or
Use a Filter for getting / manipulating the request before its send. This let's you really just change the used cookie container before actually submitting.
The Filter is set in the DefaultLoader configuration. See https://github.com/AngleSharp/AngleSharp/blob/master/src/AngleSharp/ConfigurationExtensions.cs#L152.

Django views detect if client uses webgl compatible browser

Is there any option to detect in the view function if the browser from which the user is coming is webGL compatible or not?
Detecting WebGL is a matter of using JavaScript on the frontend (see Proper way to detect WebGL support?), so I don't think there is a way to do this directly in the backend in a Django view.
What you could do is perform the detection with JavaScript on the first page the user visits and use AJAX to store the result in a server-side variable which you can use in subsequent requests to decide whether to use WebGL features or not.
Expanding on voodoo's answer, here is the javascript to quickly determine wheter a client has webgl support
var canvas = document.getElementById("canvas");
var names = ["webgl", "experimental-webgl", "webkit-3d", "mozwebgl"];
var webgl_supported = false;
for(var i in names) {
try {
gl = canvas.getContext(names[i], { });
if (gl && typeof gl.getParameter == "function") {
webgl_supported = true;
break;
}
} catch(e) { }
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/webgl_enabled_handler");
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xmlhttp.send(JSON.stringify({webgl_enabled: webgl_supported }));
This assumes that in your html page/template there's a canvas element with id "canvas".
The resulting json would be sent as a POST request to django after page loads
Unfortunately I doubt there's a way to determine webgl support through a general GET request from django

Django - jquery : populate combobox based on selection of another combobox

I am quite new to Django and jquery stuff. I am trying to populate a comboBox (ChoiceField in Django) based ont the choice selected in another comboBox (without reloading the page).
I can't find any simple example of such a basic application of ajax.
For now I'm call the following ajax function when I select an item from the first dropdown list.
function get_asset_from_type(){
var type_asset = $("#id_type").val();
var data = {type_asset:type_asset};
var args = {type:"POST", url:"/asset/etatType/", data:data};
$.ajax(args);
alert(type_asset);
return false;
};
It alerts the right type but gives a 403 error on the given url. Weird thing is this url works the first time I load the page. I don't understand what's going on..
EDIT:
403 error seems to be gone, remains the initial question :)
I think you're running up against a CSRF problem. As Django by default blocks POST requests that do not have a CSRF Token with a 403. There are a couple ways to deal with this in JS. One is to pull the value out of the cookie, the code to do that can be found here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
or you can do it by passing the CSRF_TOKEN in with the javascript script tag:
<script src='myjavascript.js?CSRF_TOKEN={{ csrf_token }}'></script>
Note that it's using a double braket, instead of {%%}. This gets the value of the token, instead of the form input.
function getOptionsFromScriptSrc() {
// Get last script tag in parsed DOM.
// Due to the way html pages are parsed,
// the last one is always the one being loaded.
var options = {}
var js_src = $('script').last().attr('src');
if(js_src.match(/\?/)) {
var options_list = js_src.split('?')[1].split('&');
for(var i = 0; i < options_list.length; i++) {
var tmp = options_list[i].split('=');
options[$.trim(tmp[0])] = $.trim(tmp[1]);
}
}
return options;
}
function get_asset_from_type(){
var options = getOptionsFromScriptSrc();
var type_asset = $("#id_type").val();
var data = {type_asset: type_asset, csrfmiddlewaretoken: options['CSRF_TOKEN']};
var args = {type:"POST", url:"/asset/etatType/", data:data};
$.ajax(args);
alert(type_asset);
return false;
};
I haven't, of course, tested this code, but I have used this method before and it works pretty well.
To the main problem of populating a select box, you need to specify a callback for your ajax post, and then deal with the data returned from your server:
function get_asset_from_type(){
var options = getOptionsFromScriptSrc();
var type_asset = $("#id_type").val();
var post_data = {type_asset: type_asset, csrfmiddlewaretoken: options['CSRF_TOKEN']};
$.post('/asset/etatType/', post_data, function(data){
// Assuming server is going to respond with the html of the options, eg: <option value="1">One</option><option value="2">Two</option>...
$('#id_ofmyselectbox').append(data);
});
};

How do I set cookies for individual pages for use with colorbox?

I have been using a script with colorbox that writes a cookie when a page is visited and only opens the colorbox on page load if the page has not been visited in the last month.
I would now like to amend this so that it writes and checks for a cookie for the specific page rather than the domain as a whole. This is because I am publishing a new page each month and would like a colorbox to open the first time a user visits the new page each month. Here is the script as it currently stands:
if (document.cookie.indexOf('visited=true') === -1) {
var expires = new Date();
expires.setDate(expires.getDate()+31);
document.cookie = "visited=true; expires="+expires.toUTCString();
$.colorbox({href:'welcome.html', width:"60%", speed:1500});
}
Could someone help me adapt this to work on a page-by-page basis,
Thanks,
Nick
I figured out how to do this:
I changed this line:
document.cookie = "visited=true; expires="+expires.toUTCString();
to this:
document.cookie = "visited=true; path=/page.php; expires="+expires.toUTCString();

Redirect Entry form in SharePoint back to itself once entry submitted?

The issue I have is that people in my group are using a link to an Entry Form to post new itmes to a SharePoint list. Everytime they click 'submit' to post new item, SharPoint redirects them to the list.
I need a solution for SharePoint to direct them to the empty Entry form instead, no matter how many times they need to use it.
Is there such solution? Thanks,
I already have this "/EntryForm.aspx?Source=http://" in the link to the Entry form, but works only 2 times, after that will direct to the list.
Essentially you need to ensure that the Source parameter is always set to EntryForm.aspx so that no matter how often you loop through the form you always get redirected back to a new one at the end. You knew this, but I am just clarifying!
Simplest method would be some javascript to test this source parameter and if its not what you want then redirect the request so it is.
If you can edit the EntryForm.aspx page in SharePoint Designer then add this javascript to the page somewhere:
<script type="text/javascript">
if (gup("ok") != 1) {
if (gup("source") != window.location.href) {
window.location = window.location.href + "?&source=" + window.location.href + "&ok=1";
}
}
function gup( name ){
//This function returns the URL parameter specified
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
Essentially this is just redirecting your requests to this page so the source is always itself. The ok parameter is just to ensure that it only does it once.
This is not perfect code, but it demonstrates the idea (and it works!)
gup (Get URL Parameter) function is taken from here and I find it really useful.
Hope it helps
Charlie