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.
Related
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"];
I have a Google Custom Search Element on my site configured to use the "Overlay Layout":
And I have a Google Analytics Profile conneced to this Google Custom Search account set under the relevant section like this:
I'm using the default Analytics code, and the Custom Search code Google vended.
Analytics "Site Search Tracking" is On at the "Reporting Views Settings" like this:
The problem:
No site search information is being collected by Analytics, even after several days.
This problem is only happening when I use the overlay Layout.
When I use a separate search results page, the query is being collected ok since the results page request is being recorded by Analytics.
With the overlay layout, the search results are being presented in an overlay Div and the query is going only through Google's Custom Search API.
The Question:
What can I do to make sure Analytics gets the keyword query?
Is there any callbak I'm missing?
Is there any thing else I'm missing?
The Solution:
After consulting with Google Support, here is the solution:
Set up the GCS account in admin console # https://www.google.com/cse
Set up in Analytics the Site Search settings as mentioned above
Use the Async Tracking Code of Analytics (Universal Analytics Code will not work as of May 2014). put it just before the closing tag. like this:
<head>
<!-- Your head tags, etc here -->
<script type="text/javascript">
var gaq;
var _gaq = gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-YY']);
_gaq.push(['_setDomainName', 'yourdoamin.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>
</head>
Put Use the GCS Tracking code you got from the admin console inside the secion
Use Custom call back to render the search box to handle custom attributes like this:
<body>
<script>
var customUIBehaviours = function(){
//your jQuery Post UI changes to the GCS box may come here
};
var renderSearchElement = function() {
google.search.cse.element.render({
div: 'gsd',
tag: 'search',
attributes:{
linkTarget:'_self',
gaQueryParameter: 'q',
gaCategoryParameter:'',
noResultsString:'No results.',
enableAutoComplete: true
}
});
};
var myCallback = function() {
if (document.readyState == 'complete') {
renderSearchElement();
customUIBehaviours();
} else {
google.setOnLoadCallback(function() {
renderSearchElement();
customUIBehaviours();
});
}
};
//this will make the GCS render by myCallback
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = 'YOUR GCS CODE HERE';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<div id="gsd" class="gsce-searchBox"></div>
</body>
More information on the GCS V2 is available # https://developers.google.com/custom-search/docs/element#cse-element
I'm developing some functionality that puts some adds on the my clients page.
I just give them some javascript that they have to add to their page.
That javascript as an identifier to the id of the add (for constructing purpose).
The javascript for every add is like this:
var _adds = _adds || [];
_adds.push(['ID_OF_THE_ADD_XXXXX']);
(function() {
var script = document.createElement('script');
script.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.myswebsite.com/myjs.js';
script.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(script);
})();
So, the hard part is that myjs.js is added many times to the head of client's page.
I already tried to declare some variable com myjs.js and check that var here but without success because everything is async.
Is there a way to not duplicate this?
Thanks in advance.
okay just got that before loading the prev script it is getting executed again so try this.
var _adds = _adds || [];
_adds.push(['ID_OF_THE_ADD_XXXXX']);
(function() {
if(typeof window.checker ==='undefined'){
window.checker = true;
var script = document.createElement('script');
script.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.myswebsite.com/myjs.js';
script.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(script);
}
})();
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
I have been building script tag using javascript.when I use this script to load the three other scripts,the script is not loading in order.I want jquery.min.js to get loaded first. So I have used that as the first parameter. But it is not getting loaded at first. so I have been caught up with reference error. Can anyone tell me what mistake I have done in this code. My code is here
<script type="text/javascript">
(function (a, b, c) {
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://') + a;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + b;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + c;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
})('ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', '.example.com/js/script.js', '.example.com/js/form.js');
</script>
Use require.js for dynamic script loading.It will work.Also, try to use jquery.js above the website rather generate using script.
After my studing around this toppics, I updated for who visit to this question later.
For most of the browsers (IE9, Firefox, Chrome, Safari, ...) except Opera (12.16), dynamic script injection into DOM will load script asynchronously.
So this code:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
}
loadScript('script1.js');
loadScript('script2.js');
loadScript('script3.js');
is almost equivalent to:
<script src="script1.js" async></script>
<script src="script2.js" async></script>
<script src="script3.js" async></script>
But if the async flag is set to false explicitly like:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.async = false;
}
then the scripts will be loaded in order synchronously.
So the very short answer for this question is that g.async = false, but still I also recommend to use some framework and that is the best answer.
Try this: http://jsfiddle.net/DRCzN/
~~~~ original answer ~~~~~~
Dynamic script insertion (createElement('script') then insertBefore() or even insertAfter()) will load each script asynchronously.
So with your current script, the arrival of those script to the browser heavily depends on the network status.
If you want keep the dependency of these scripts, you can use some script loader such as $script, head.js or Require.js.
EDIT: I like Jonathan's solution, and here is a little improvement using $.getScript().
if script.js and form.js are independent of each other
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.each(scripts, function(i, s) {
$.getScript(protocol + s);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
if form.js depneds on script.js
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.getScript(protocol + scripts[0], function() {
$.getScript(protocol + scripts[1]);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
It's close, but use insertAfter, and remember to increase the index for each script.
var s = document.getElementsByTagName('script')[0];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[1];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[2];
g.parentNode.insertBefore(s, g.nextSibling);
Here's another example. This one uses an array of scripts to add, reverses them and then inserts after the current script tag.
EDIT: Can you get away with loading jQuery directly, as below. Using // a the start will make the resource load under the current protocol.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function (scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.'),
thisScript = document.getElementsByTagName('script')[0];
function createScriptTag(element, index, array) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = protocol + element;
thisScript.parentNode.insertBefore(newScript, thisScript.nextSibling);
};
(scripts || []).reverse().forEach(createScriptTag);
})(['example.com/js/script.js', 'example.com/js/form.js']);
</script>
Here is another method of solving this problem :
<script type="text/javascript">
window.onload = function () {
"use strict";
function js(n) {
var s = document.createElement('script');
s.setAttribute("type", "text/javascript");
s.setAttribute("src", n);
document.getElementsByTagName("head")[0].appendChild(s);
}
js("http://requirejs.org/docs/release/2.1.8/minified/require.js");
js("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
js("http://www.example.com/form.js");
js("http://www.example.com/script.js");
};
</script>
This can also be used rather than the code explained in question.