I want to create a simple tracking script to give to my clients. Something similar with GA but very basic.
The requirements are
give the clients a single and simple js script like google Analytics does
make most of the logic inside the js file loaded by 3th party sites from the main site
collect in PHP the information and store it
What I can't figure yet is what are the ways to do this?
Google from what I see is loading a gif file, stores the information and parses the logs.
If I do something similar sending the data to a php file Ajax cross site policy will stop me, from what I remember.
So what is a clean way to do this ? ( I don't need code just the logic behind it )
Method a - web bug:
Give the user this:
<img src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid" width="1" height="1" />
have the php return header("content-type:image/gif"); and serve them a gif file for their effort.
Method b - script
Create a php file that can parse parameters and have it return content-type:text/javascript
Have them load it like this:
<script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>
If you want to you can do additional stuff like
<script type="text/javascript">
var associateId = "12345";
var trackingPage="homepage";
</script>
<script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>
then in the php have code like this (watch the nested quotes)
$str = 'var url = "http://www.yourserver.com/moretracking.php?associateid="+associateId+';
$str .= '"&page="+trackingPage+"&ref="+escape(document.referrer);\n';
$str .= 'document.write(\'<img src="\'+url+\'"/>\');';
echo $str;
You may read this (found googling) about cross domain ajax and its possible solutions... http://snook.ca/archives/javascript/cross_domain_aj/
Well, i use some php code that is included in my script that logs Ip Addresses and as much information i can get from a server-side perspective. It saves it in a MySql Database. I also use a Ajax script to post data to a php script, the data in this case is Screen Heigth and thing you only can get client-side.
Related
Good evening internet peoples ;)
I have a series of Javascript commands, which will set variables using different methods.
From an XML file I have output the contents of a URL and Site name to an overflow table.
This creates hyperlinks with tooltips etc. outputting to a frame in center of the page.
I am stuck on the following:
var ipaddress = [OBTAIN IPADDRESS OF SITE FROM XML FILE???];
From the XML file, I want to run a PHP section of code to obtain the IPAddress of the site, output the result to a table cell and then move onto the next record within the XML file.
This is the PHP I would like to employ to obtain the various sites IPAddress (Which works beautifully):
<?php
$ipInfo = dns_get_record('google.co.uk', DNS_A);
$ip = $ipInfo[0]['ip'];
print_r($ip);
?>
So the main question is this....How can I run the above PHP coding after reading XML file and set the IPAddress variable? Do I make sense :S
This is pretty simple. In PHP, just do:
header('Content-Type: application/javascript');
echo 'var ipaddress=', json_encode($ip), ';'
Always JSON-encode arbitrary data you want to pass to JavaScript, so that escaping happens for you automatically.
Now, you have to load this script somehow. One simple way is to drop this in your HTML:
<script src="yourScript.php"></script>
To be clear, you aren't running your PHP from JavaScript. You're using PHP to dynamically create JavaScript.
Just to reiterate Fire-Dragon-DoL's comment in a way that may help you get started.
<head>
... other stuff
<script type="text/javascript">
<?php
$ipInfo = dns_get_record('google.co.uk', DNS_A);
$ip = $ipInfo[0]['ip'];
echo 'var ipAddress = "' . $ip . '";';
?>
</script>
</head>
<body>
.... all your existing stuff
So you are basically creating javascript from within the PHP code running on the server, but as its placed in the document it runs just like you had written it manually into the head of the html document.
The variable ipAddress will be available to all your other javascript's as it will be placed globally. So you can just use it in any other javascritp that loads after this new section.
I would like to load an external file using javascript. I'm planning to add ad codes in the external file and include it using javascript wherever necessary. This will help me to change ad codes easily when the need arises.
Also I believe various third party solutions such as Google Admanager are complex and unnecessary. So I need your suggestion for the same.
Note : The external file may contain PHP / Javascript source.
What I thought was to add something like this ...
document.write("<script type='text/javascript' src='ad1.js'></script>");
What's your opinion ?
Correct me if I'm wrong, but it sounds like you want to display ad codes separate from the content of the page (such as in iframes). Most ad providers don't like this, since the ads displayed won't be relevant to site content.
Another way to do it however (that makes everyone happy) is to use php's include statement and include the external file. This will dump the contents of the page into the current page, so make sure you don't have multiple <html> elements or inaccurate paths.
I wouldn't use document.write, is that would overwrite the content already on the page, thus making your solution quite static. Try this instead:
function addScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.head.appendChild(script);
}
You'll want to make sure that the page has loaded enough that the document.head is defined. You could use an event listener for this.
I'm building a sort of analytics platform for fun this weekend and here is my desired effect.
Client: abc.com
Server: test.com
User visits http://abc.com/#12345
Client sends Server via javascript id: 12345, and browser information. Server responds with a new id (ex: #23456), which is then pushed onto the current url (pushstate) http://abc.com/#23456
I was thinking of some kind of script that the Client includes from the Server that communicates with the servers backend, but is that not techincally XSS and unsecure? How do analytics people (Google, GetClicky, etc) do it?!
How can I achieve this like analytics sites do so the internet gods don't get mad at me for XSS, while still maintaing security, and ease of implementation. One included source.
I'd love anything you can do to point me in the right direction.
With jsonp. The idea is that the source of a script tag is the code you want to execute:
<script type="text/javascript" src="http://yoursite.com?id=12345&this=that" />
edit: Yes, you create the script dynamically similar to an ajax response:
function getResponse(id){
var scrpt = document.createElement("script");
scrpt.type="text/javascript";
scrpt.src = "http://yoursite.com?id="+id;
document.body.appendChild(scrpt);
}
Inside your php page:
<?PHP
if(!isset($_GET['id']))die();
$id = $_GET['id'];
echo "alert('$id');";
?>
Something of the sort, anyway.
edit: completely forgot, but the point of jsonp is that you pass in a callback function. See here for some php documentation: http://php.net/manual/en/function.json-encode.php
I have a little problem here, and no tutorials have been of help, since I couldn't find one that was directed at this specific problem.
I have 2 hosting accounts, one on a server that supports PHP. And the other on a different server that does not support PHP.
SERVER A = PHP Support, and
SERVER B = NO PHP Support.
On server a I have a php script that generates a random image. And On server b, i have a html file that includes a javascript that calls that php function on server a. But no matter how I do it, it never works.
I have the following code to retrieve the result from the php script:
<script language="javascript" src="http://www.mysite.com/folder/file.php"></script>
I know I'm probably missing something, but I've been looking for weeks! But haven't found any information that could explain how this is done. Please help!
Thank you :)
UPDATE
The PHP script is:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
echo '<img src="'.doitnow($theimgs).'" alt="something" />';
<img src="http://mysite.com/folder/file.php" alt="" /> ?
It's not clear, why you include a PHP file as JavaScript. But try following:
Modify your PHP Script so that it returns a image file directly. I'll call that script image.php. For further information, look for the PHP function: header('Content-type: image/jpeg')
In your JavaScript file use image.php as you would any normal image.
Include the JavaScript on server B as a *.js file.
UPDATE:
It's still not clear, why you need JavaScript.
Try as image.php:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/" . doitnow($theimgs));
And on server b:
<img src="www.example.org/image.php"/>
You didn't specify, but I assume the two servers have different domain/hostnames. You may be running into a browser security model problem (same origin policy).
If that's the case, you need to use JSONP.
You may be using outdated sources to learn, since the language attribute is deprecated and you should use type="text/javascript" instead. It's also not clear what kind of output does the .php script produce. If it's image data, why are you trying to load it as a script and not an image (i.e., with the <img> tag)?
Update: The script is returning HTML, which means it should be loaded using Ajax, but you can't do that if it's on a different domain due to the same origin policy. The reason nothing is working now is that scripts loaded using the <script> tag aren't interpreted as HTML. To pass data between servers, you should try JSONP instead.
It seems that server A generates an HTML link to a random image (not an image). The URL is relative to wherever you insert it:
<img src="images/logo.png" alt="something" />
That means that you have an images subdirectory everywhere you are using the picture. If not, please adjust the URL accordingly. Forget about JavaScript, PHP or AJAX: this is just good old HTML.
Update
The PHP Script displays pics randomly.
Pics are hosted on server A, and they
are indeed accessible and readable
from the internet. The PHP Script has
been tested by itself, and works.
If these statements are true, Māris Kiseļovs' answer should work. So either your description of the problem is inaccurate or you didn't understand the answer...
I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
What are the advantages (or disadvantages) to including Javascript like this?
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
If you don't need it, don't use it:
The first thing you need to keep in
mind is YAGNI. You Ain't Gonna
Need It. Until a certain feature,
principle, or guideline becomes useful
and relevant, don't use it.
Disadvantages:
Added complexity
Slower than static files.
Caching problems (server side)
Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)
Advantages:
User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
Page specific javascript - JS could also be generalized to use parameters
JSON created from database (usually requested via AJAX)
Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.
Also:
This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).
That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.
Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:
fake_js.php:
<?php
header('Content-type: text/javascript')
include('the_real_javascript.js');
?>
A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.
In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.
Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.
An example usage would be population of an array based on the contents of a DB table.
Or application of localization techniques.
If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):
<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...
You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.
Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.
You could do something like this in your html:
<script type="text/javascript">
registry = {
myString : '<?php echo $somePhpString; ?>',
myInt : <?php echo $somePhpInteger; ?>
}
</script>
And then do something like this in your js:
if (registry.myInt === 1) {
alert(registry.myString);
}