Getting Weird responseText - javascript

I've a very short php code written just for testing the ajax in a Cordova application.
Code for php is :
<?php
if (isset($_POST["TEST"])){
if ($_POST["TEST"] == "TEST"){
$resp["GOOD"] = "TEST WORKS!!";
echo (json_encode($resp));
}
}
?>
My request code is :
$.post('http://mobtest.bugs3.com/test.php',
{ TEST: 'TEST' },
function (result) {
console.log(result);
$('#txtlbl').text(result);
}
);
I am expecting the responseText to be "TEST WORKS!!" but what I get is :
{"GOOD":"TEST WORKS!!"}<!-- www.serversfree.com Analytics Code -->
<script src="http://www.serversfree.com"></script><noscript><a title="Free hosting servers" href="http://www.serversfree.com">Free servers</a><a title="Free websites hosting server" href="http://www.serversfree.com">Free websites hosting server</a><a title="Free hosting server features" href="http://www.serversfree.com/server-features/">Free server features</a><a title="Free hosting" href="http://www.bugs3.com">Free hosting</a><a title="Page rank" href="http://www.1pagerank.com">Page rank</a></noscript>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24425628-3']);
_gaq.push(['_setDomainName', window.location.host]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="http://www.bugs3.com/ganalytics.js"></script>
<!-- End Of Analytics Code -->
I don't understand whats happening here.

The answer here might solve your problem:
https://stackoverflow.com/a/10768130/1696795
In short user cleong wrote:
The code is in a PHP auto-append file. It doesn't get executed if you exit explicitly instead of letting the script reach the end of the file.
so just append this to the end of your php code:
exit();

for some reason, you are trying to echo your whole array.
update: plus you use json_encode while trying to access the result directly in your javascript.
so just echo the variable in your php code:
echo $resp["GOOD"];

Related

Code Not Tracking Email Enquiries In Google Analytics

I am trying to get email enquiries submitted through the website to show up in Analytics as a tracked event.
This client has multiple domains so we are tracking which email enquiry came from which site.
This is the code created so far. (please note we use coldfusion to pull from our CMS system)
<!-- Analytics Tracking Code-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<cfif isdefined ("getsite.contact") AND getsite.contact NEQ "">#getsite.contact#<cfelse>UA-109409-1</cfif>']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google- analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!--Email Tracking Code in Analytics -->
<script type="text/javascript">
jQuery(document).ready(function($){
$('form').submit(function(event){
//if analytics object exists
if(window._gat){
event.preventDefault();
optinForm = this;
_gaq.push(['_set','hitCallback', function(){
optinForm.submit();
}]);
_gaq.push(['_trackEvent', 'Email Enquiry', 'Form Submitted', '#getsite.domain#']);
}
//if no analytics object, service as normal
});
});
</script>
Any assistance would be great.

PHP as JavaScript: get users IP

I use this simple script:
<script type="text/javascript">
var _mytrack = _mytrack || [];
_mytrack.push(['_setType', 'SOMETYPE']);
_mytrack.push(['_setEmail', 'john#johndoe.com']);
(function() {
var mytrack = document.createElement('script');
_mytrack.type = 'text/javascript';
_mytrack.async = true;
mytrack.src = ('https:' == document.location.protocol ? 'https://www' : 'http://www') + '.mytrack.net/tracker.tell.php?i='+_mytrack;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mytrack, s);
})();
</script>
My PHP script (tracker.tell.php) looks like this:
header("content-type: application/javascript");
echo "alert('".$_SERVER['REMOTE_ADDR']."');";
Now the question is related to the $_SERVER['REMOTE_ADDR'] because this gives (in an JS alert) the IP of the SERVER and not of the CLIENT.
$_SERVER['REMOTE_ADDR'] does give you the IP address of the remote user. But if you are using a proxy or load balancer, you should use $_SERVER['HTTP_X_FORWARDED_FOR']
If users can reach your server directly or through a proxy then just use an if statement
$remote_ip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
then pass the variable to JS.

What is the code to use google analytics in seperate .js file?

I read somewhere that placing google analytics tracking code in seperate file is not recommended but I have no idea how to use it for my website (there are .php files and .tpl files and if I tried to put it almost everywhere and there was an error or it didn`t track the visitors).
Could anyone tell me which code I should put into separate .js file and in .tpl file so at least the basic functions would work? Thanks a lot!
This is the cleanest (using a anonymous auto-executing function):
(function() {
var _gaq = window._gaq = window._gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Then reference in either your head or before end of body via:
<script type="text/javascript" src="YOUR_GA_CODE_LOCATION.js"></script>
you can write google analytics code in separate js file and include that js and call its function -
Suppose, following code is written in mygoogle.js
function loadMyGoogle()
window._gaq = window._gaq || [];
window._gaq.push([ '_setAccount',
'setaccounthere']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
}
then in your php files in header -
<head>
<include script="mygoogle.js">
</head>
In onload function of body tag -
function onload(){
loadMyGoogle();
}
I hope you know how you can set onload event in body tag
Do not put GA code in .js file instead include html page.
Steps:
1) Open notepad and paste GA code there.
2) Save it as HTML page
3) Include that html before end of head tag

Google Analytics Tracking Code Will Not Fire on "3rd Party" Domain

The tracking code on the site in question, "site2", appears as follows:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName', 'site1.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
Here is a screenshot of the debugger on that site:
The _setDomainName method on the preceding domain, "site1" has a period before it:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName', '.site1.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
While this may or may not prevent cookies from being passed along to the second domain, the tracking code should still at least fire, no? It is important to note that we own both domains. I cannot find any reason that would cause the code not to trigger, except perhaps an error elsewhere on the page. I am using GA Debug to see whether or not the beacon is being sent. It's being sent on site1, but not on site2.
Thanks for the help!
_setDomainName tells the Google Analytics cookie where to store itself. Browsers will not let set a cookie on site1.com from site2.com. Leave .site1.com on you main site and update it to .site2.com on your second.
If you'd like visit data between domains, you have to do one of the following:
Tag the links between the domains using linkByPost etc... Read the google documentation about it here: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingSite
OR I'd recommend looking into Google Analytics on Steroids as they solve this use case more elegantly: https://github.com/CardinalPath/gas#cross-domain
I don't believe that you need the period before the domain name. According to the google analytics guide you should use the following formatting.
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12345-1']);
_gaq.push(['_setDomainName', 'example-petstore.com']);
_gaq.push(['_trackPageview']);
</script>
https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingSite#domainSubDomains

Javascript Redirect with Google Analytics

I need help figuring out how to successfully redirect while including Analytics code.
I have a subdomain setup http://buuf.fractalsystems.org
The subdomain is actually just a subfolder http://fractalsystems.org/buuf
I have an HTML file in that subfolder which redirects to https://market.android.com/developer?pub=Fractal%20Systems
The code for that redirect file:
<head>
<script type="text/javascript">
function delayedRedirect(){
window.location = "https://market.android.com/developer?pub=Fractal%20Systems"
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']); <!--I have my real ID there-->
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body onLoad="setTimeout('delayedRedirect()', 3000)">
<h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 3 seconds.</h2>
</body>
</html>
This works as a redirect only if I don't include my Analytics code. I've tried moving the code around with no change.
QUESTION
How can I add a redirect, of any kind, and still be able to track with Google Analytics?
I've tried PHP redirects with no success and am pretty sure htaccess redirects wont help although I'm open to suggestions.
The reason I'm using a JavaScript redirect is so I can continue to track with Google Analytics and also show a little message or make a custom page with the delay.
Thanks for any help. Doesn't have to be JS, please, any input is welcome if you know of a solution.
Note: _gaq.push allows pushing of functions onto the queue. The following code should redirect after 250 milliseconds (to allow time for the tracking pixel) after the _trackPageview:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
setTimeout(function() {
window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
}, 250);
});
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
If you're using the new GA code you can simply replace this line ga('send', 'pageview'); with this code:
ga('send', 'pageview', {
'hitCallback': function() {
window.location = "http://www.your-site.com";
}
});
Example in full:
(function(i,s,o,g,r,a,m){
i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments)
},i[r].l=1*new Date();
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;
a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxxx-2', 'auto');
ga('send', 'pageview', {
'hitCallback': function() {
window.location = "http://www.your-site.com";
}
});
I'd suggest changing your Google Analytics code to be synchronous instead of asychronous by changing it to this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
This should guarantee that it runs before your redirect code kicks in and it should be out of the way of your redirect script so there is no interference. As you have it now, you're playing a guessing game for how long the GA script will take to load and that it will load and do it's job in under 3 seconds. That may usually be the case, but there is no reason to load it asynchronously like you are and have to play that game. Load it synchronously and it will do it's job before your javascript redirect fires.
It might even be possible to just put the redirect directly after the GA code like this and minimize the time that your placeholder page is displayed:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
</script>
The code provided by Mike works indeed. However, I found that removing the timer entirely works as well. The __utm.gif request is then aborted, but all information has been sent. The window just redirects and doesn't wait for the reply (which is simply a 200 status). I tested this and it seems to be working nicely.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
});
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Using meta refresh worked like a charm! Legacy FTW! Thanks, #Balexandre
<html>
<head>
<meta http-equiv="refresh" content="5; url=https://market.android.com/developer?pub=Fractal%20Systems">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 5 seconds.</h2>
</body>
</html>
RECAP: I am now able to redirect while tracking those redirects using Google Analytics!
Meta Refresh (Taken from wikipedia)
Examples
Place inside to refresh page after 5 seconds:
<meta http-equiv="refresh" content="5">
Redirect to http://example.com/ after 5 seconds:
<meta http-equiv="refresh" content="5; url=http://example.com/">
Redirect to http://example.com/ immediately:
<meta http-equiv="refresh" content="0; url=http://example.com/">
Meta refresh is generally discouraged because of usability concerns (especially with a short, or no delay), but as a fallback for clients with no javascript I think it's perfectly valid in this case.
If you combine the synchronous ga.js call with a meta refresh you get the best of both worlds: an almost instant, tracked redirect if JS is enabled; a delayed but still effective redirect if not (and a hard link in the body just in case all else fails).
<html>
<head>
<!--For JS disabled: decent delay, both for usability and to allow plenty of time for JS to work if enabled -->
<meta http-equiv="refresh" content="5;https://market.android.com/developer?pub=Fractal%20Systems"/>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
</script>
<!--Synchronous call to ensure tracking fires before JS redirect-->
<script type="text/javascript" src="//www.google-analytics.com/ga.js"></script>
<script>
/* if JS is enabled this will normally fire well before the meta refresh delay ends: an almost instantaneous redirect */
window.location="https://market.android.com/developer?pub=Fractal%20Systems";
</script>
</head>
<body>
<!-- Include a hard link in case both js and the meta refresh fail -->
<p>Redirecting you to https://market.android.com/developer?pub=Fractal%20Systems</p>
</body></html>
There's a good answer here:
https://www.domsammut.com/code/setting-up-hitcallback-using-google-universal-analytics
In short, you'd do it using an event, and you use the hitCallback function.
This approach does not require a delay. First execute google analytics code synchronously and then redirect.
<html>
<head>
<script src="//www.google-analytics.com/analytics.js"></script>
<script>
var tracker = ga.create('UA-xxxxxxxx-x', 'auto');
tracker.send('pageview');
window.location='http://your-url.com';
</script>
</head>
<body>
</body>
</html>
I think maybe just use jquery ready method so it won't start the timer till the page is fully loaded...
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
setTimeout(function() {
//alert("redirecting!");
window.location = '<?= $url ?>';
}, 3000);
});
</script>

Categories