Tracking outgoing links with Javascript and PHP - javascript

I have tried it using jQuery but it is not working.
<script>
$("a").click(function () {
$.post("http://www.example.com/trackol.php", {result: "click"
}, "html");
});
</script>
out

To get the best results you should change two things in your approach
Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.
So the solution would be something like this:
<script>
$(document).ready(function() {
$("a").mousedown(function (){
new Image().src= "http://www.example.com/trackol.php?result=click";
});
});
</script>
out

Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:
out
and in the PHP script, after you do your tracking stuff:
...
header("Location: $dest");

As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:
This works:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tracking outgoing links with JavaScript and PHP</title>
</head>
<body>
<p>Test link to Google</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$('a').click(function() {
$.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
});
});
</script>
</body>
</html>
See it in action here: http://jsbin.com/imomo3

Related

click on an image link when a web page is opened using javascript

I'm new in Javascript and this is my code
<!DOCTYPE html>
<html>
<body>
<img src="http://www.example.com/1/img" border="0" />
<script>
function () {
document.getElementById('test').click();
};
function();
</script>
</body>
</html>
I was trying to open that link when the web page is loaded but I make some errors. Any help?
The way you define and invoke function is not correct. This is invalid syntax construction as function declaration (statement staring with function keyword) requires a name to be valid javascript code.
So you either give function a name an invoke it:
function somename() {
document.getElementById('test').click();
};
somename();
.. or use IIFE (immediately-invoked function expression):
(function() {
document.getElementById('test').click();
})();
However, in your case you don't really need as you don't use it for what it's really useful, i.e. creating new scope. Simple line
document.getElementById('test').click();
would be just enough.
You don't need the example function... remove onclick="example(this)...". Since you are clicking via javascript, the normal function of the click is to go to the link specified in the href attribute anyway.
If you just want to open a new link on page load, you can also remove all the body and just use the following:
<body>
<script>
window.location.assign = "http://example.com";
</script>
</body>
Do it like this:
<!DOCTYPE html>
<html>
<body>
asdf
<script>
document.getElementById('test').onclick();
function yourfunction(){
alert("clicked");
}
</script>
</body>
</html>
What we do here is assigning the function "yourfunction()" to "onclick" of your anchor (the element). Due to the fact that your code is automatically executed when you reload the page (note that we've just posted a line of code into the script tag) you can trigger the onclick event just by using ".onclick()".
However, you're executing "yourfunction()" every time you reload the page and as you click your anchor.
The function itself is pretty boring. It just makes an alert (small window with a message and ok button) which says "clicked".
Further reading:
How can I trigger a JavaScript event click
https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onclick
https://developer.mozilla.org/de/docs/Web/API/Window/alert
Some further advice. I think you are trying to achieve a "redirection" to another site as soon as you got to a domain. You probably want to do stuff like redirecting a typo ("gogole.com") to your "real" domain (google.com). This shouldn't be done with Javascript! You have to configure your webserver to do so (it's pretty easy). See this for example.
However, ther is also another approach to achieve this:
<meta http-equiv="refresh" content="0; url=http://www.example.com/">
Put this line of code into the of your document.

How to load an external JS library that has code between <script> tags using jQuery

The original code I have is
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: qwerty
</script>
I want to make this code happen using jQuery after something has been triggered. Something like this
jQuery.getScript('http://platform.linkedin.com/in.js');
The problem is that I am not sure what the api_key part does, I've never seen the combination of a request to external lib and code between script tags. Is there a way to imitate that with jQuery? And also - what does that line do? :)
Thanks!
It's not exactly the answer to the question I originally posted, which is more abstract. But in case someone stumbles on this question in connection to linkedin, here's the way to load their framework asynchronously.
jQuery.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
IN.init({
api_key: "qwerty"
});
});
I did some digging through what happens when you load the script, and found that in.js parses the contents of the tag whose src is itself and uses them to build a new script tag to append to the head.
Based on your post, it appended
<script src="https://www.linkedin.com/uas/js/userspace?v=0.0.2000-RC1.20888-1402&apiKey=qwerty&"></script>
to the head. userspace.js obviously rejected the api key, but because this is a proprietary method of loading data, I can't predict how it'll work if and when you try to turn that into an ajax call.
Update:
According to the script tag standard, "If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI." This allows LinkedIn to get away with putting invalid Javascript inside the script tag, knowing it'll never get evaluated by the browser.
This should work correctly on jQuery mobile site.
<script type="IN/Apply" data-companyname="XXX" data-jobtitle="XXX" data-joblocation="XXX" data-email="XXX#XXX.XXX">
</script>
<script type="text/javascript">
$(function() {
if(typeof(IN)=="undefined"){
$.getScript("//platform.linkedin.com/in.js?async=true", function success() {
IN.init({api_key: "XXX"});
});
}
else{
IN.parse();
}
});
</script>

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Adding a loading gif when submitting form?

While my code calculates, Id like the submit button to go from the "RUN" that it is now to the loading gif that I have. Now when I click the RUN button, I also need a certain script to run which calculates all sorts of data and returns it back to the page. I wrote a function that holds the other two function and calls them in sequence. I even added a 3rd function that would revert back the submit button but I can't seem to figure this out.
The website is www.fsaesim.com/simulation.html which would be much easier to see the code, however attached is the code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
var results = Main($("#vehicleWeightTxt").val(), $("#tireChoiceSel").val(), $("#wheelBaseTxt").val(), $("#wheelRadiusTxt").val(), $("#trackWidthTxt").val(), $("#hcgTxt").val(), $("#weightDistributionTxt").val(), $("#shiftRpmTxt").val(), $("#ntTxt").val());
$('#outputTotalTime').empty();
$('#outputTotalPoints').empty();
$('#outputFuelUsed').empty();
$('#outputTimeOpenThrottle').empty();
$('#outputCorneringTimeTotal').empty();
$('#outputTotalStraightSectionTime').empty();
$('#outputTotalNumberOfShifts').empty();
$('#outputTractionLimitedDuration').empty();
$('#outputMeanLongAccel').empty();
$('#outputMeanHorsepower').empty();
$('#outputAccelerationTime').empty();
$('#outputMeanAccelerationLongAccel').empty();
$('#outputAccelerationTractionLimitedTime').empty();
$('#outputAccelerationTotalPoints').empty();
$('#outputAccelerationWideOpenThrottlePercentage').empty();
$('#outputAccelerationShifts').empty();
$('#outputAccelerationTrapSpeed').empty();
$('#outputTotalEnduranceTime').empty();
$('#outputTotalEndurancePoints').empty();
$('#outputTotalEnduranceFuelUsed').empty();
$('#outputTotalWOTPercentage').empty();
$('#outputTotalEnduranceShifts').empty();
$('#outputTotalEnduranceTractionLimitedTime').empty();
$('#outputTotalEnduranceAcceleration').empty();
$('#outputSkidpadTime').empty();
$('#outputSkidpadPoints').empty();
$('#outputSkidpadVelocity').empty();
$('#outputSkidpadAcceleration').empty();
$('#outputAutocrossTime').empty();
$('#outputAutocrossPoints').empty();
$('#outputAutocrossTotalShifts').empty();
$('#outputAutocrossTractionLimitedTime').empty();
$('#outputAutocrossVelocity').empty();
$('#outputAutocrossWOTPercentage').empty();
$('#outputAutocrossLongitudinalAcceleration').empty();
$('#outputMaxHorsepower').empty();
$("#outputTotalTime").append(results.output1);
$("#outputTotalPoints").append(results.output2);
$("#outputFuelUsed").append(results.output3);
$("#outputTimeOpenThrottle").append(results.output4);
$("#outputCorneringTimeTotal").append(results.output5);
$("#outputTotalStraightSectionTime").append(results.output6);
$("#outputTotalNumberOfShifts").append(results.output7);
$("#outputTractionLimitedDuration").append(results.output8);
$("#outputMeanLongAccel").append(results.output9);
$("#outputMeanHorsepower").append(results.output10);
$("#outputMaxHorsepower").append(results.output27);
$("#outputAccelerationTime").append(results.output11);
$("#outputMeanAccelerationLongAccel").append(results.output12);
$("#outputAccelerationTractionLimitedTime").append(results.output13);
$("#outputAccelerationTotalPoints").append(results.output14);
$("#outputAccelerationWideOpenThrottlePercentage").append(results.output15);
$("#outputAccelerationShifts").append(results.output16);
$("#outputAccelerationTrapSpeed").append(results.output17);
$("#outputTotalEnduranceTime").append(results.output1);
$("#outputTotalEndurancePoints").append(results.output2);
$("#outputTotalEnduranceFuelUsed").append(results.output3);
$("#outputTotalWOTPercentage").append(results.output4);
$("#outputTotalEnduranceShifts").append(results.output7);
$("#outputTotalEnduranceTractionLimitedTime").append(results.output8);
$("#outputTotalEnduranceAcceleration").append(results.output9);
$("#outputSkidpadTime").append(results.output18);
$("#outputSkidpadPoints").append(results.output19);
$("#outputSkidpadVelocity").append(results.output20);
$("#outputSkidpadAcceleration").append(results.output21);
$("#outputAutocrossTime").append(results.output22);
$("#outputAutocrossPoints").append(results.output23);
$("#outputAutocrossTotalShifts").append(results.output24);
$("#outputAutocrossTractionLimitedTime").append(results.output25);
$("#outputAutocrossVelocity").append(results.output26);
$("#outputAutocrossWOTPercentage").append(results.output4);
$("#outputAutocrossLongitudinalAcceleration").append(results.output9);
}
function mouseClick() {
document.getElementById("submitButton").src = "images/loading.gif";
}
function revertBack() {
document.getElementById("submitButton").src = "images/simulationSubmit.png";
}
function simulationEvents() {
mouseClick();
ShowCalculation();
revertBack();
}
</script>
<center><img src="images/simulationSubmit.png" alt="" id="submitButton" onmouseover="mouseOver()" onmouseout="mouseOut()" onclick="simulationEvents(); return false;" /></center>
Since all your processing is being done in javascript, that will tie up your script until it finishes.
Javascript isn't multithreaded, it does one task at a time until that task is done.
Generally, when you see that animated gif while a form is being processed the page is using AJAX or something similar. The number crunching is happening server-side using PHP or Python or something like that.
The animation just runs while the javascript waits to hear back from the server-side script.
You might be able to work around it somewhat with this tutorial but that seems like overkill for this situation. The easiest thing would probably be to send the form data to a server-side script or just deal with not having an animation during processing.
Edit: If you're wanting to learn how to do AJAX, here's a tutorial that uses jQuery, which your site is already loading.

JavaScript TinyMCE/jQuery race condition on firefox

I have a website with a form that uses TinyMCE; independently, I use jQuery. When I load the form from staging server on Firefox 3 (MacOS X, Linux), TinyMCE doesn't finish loading. There is an error in Firefox console, saying that t.getBody() returned null. t.getBody(), as far as I understand from TinyMCE docs, is a function that returns document's body element to be inspected for some features. Problem doesn't occur when I use Safari, nor when I use Firefox with the same site running from localhost.
Original, failing JavaScript-related code looked like this:
<script type="text/javascript" src="http://static.alfa.foo.pl/json2.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.ui.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({ mode:"specific_textareas", editor_selector:"mce", theme:"simple", language:"pl" });
</script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.jeditable.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.tinymce.js"></script>
<script type="text/javascript" charset="utf-8" src="http://static.alfa.foo.pl/foo.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ });
</script>
I tried changing script loading order, moving tinyMCE.init() call to the <script/> tag containing $(document).ready() call—before, after, and inside this call. No result. When tinyMCE.init() was called from within $(document).ready() handler, the browser did hang on request—looks like it was too late to call the init function.
Then, after googling a bit about using TinyMCE together with jQuery, I changed tinyMCE.init() call to:
tinyMCE.init({ mode:"none", theme:"simple", language:"pl" });
and added following jQuery call to the $(document).ready() handler:
$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });
Still the same error. But, and here's where things start to look like real voodoo, when I added alert(i); before the tinyMCE.execCommand() call, alerts were given, and TinyMCE textareas were initialized correctly. I figured this can be a matter of delay introduced by waiting for user dismissing the alert, so I introduced a second of delay by changing the call, still within the $(document).ready() handler, to following:
setTimeout('$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });',1000);
With the timeout, TinyMCE textareas initialize correctly, but it's duct taping around the real problem. The problem looks like an evident race condition (especially when I consider that on the same browser, but when server is on localhost, problem doesn't occur). But isn't JavaScript execution single-threaded? Could anybody please enlighten me as to what's going on here, where is the actual problem, and what can I do to have it actually fixed?
The browser executes scripts in the order they're loaded, not written. Your immediate scripts -- tinyMCE.init(...) and $(document.ready(...)); -- can execute before the files finish loading.
So, the problem is probably network latency -- especially with 6 separate scripts (each requiring a different HTTP conversation between the browser and server). So, the browser is probably trying to execute tinyMCE.init() before tiny_mce.js has finished being parsed and tinyMCE is fully defined.
If don't have Firebug, get it. ;)
It has a Net tab that will show you how long it's taking all of your scripts to load.
While you may consider the setTimeout to be duct taping, it's actually a decent solution. Only problem I see is that it assumes 1 second will always fix. A fast connection and they could see the pause. A slow connection and it doesn't wait long enough -- you still get the error.
Alternatively, you might be able to use window.onload -- assuming jQuery isn't already using it. (Can anyone else verify?)
window.onload = function () {
tinyMCE.init(...);
$(document).ready(...);
};
Also, was that a direct copy?
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ }
</script>
It's missing the ) ending ready:
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ })
</script>
Missing punctuation can cause plenty of damage. The parser is just going to keep reading until it finds it -- messing up anything in between.
Since this is the first page which came in google when I asked myself the same question, this is what i found about this problem.
source
There's a callback function in tinyMCE which is fired when the component is loaded and ready. you can use it like this :
tinyMCE.init({
...
setup : function(ed) {
ed.onInit.add(function(ed) {
console.log('Editor is loaded: ' + ed.id);
});
}
});
If you are using jquery.tinymce.js then you don't need tiny_mce.js because TinyMCE will try to load it with an ajax request. If you are finding that window.tinymce (or simply tinymce) is undefined then this means that the ajax is not yet complete (which might explain why using setTimeout worked for you). This is the typical order of events:
Load jquery.js with a script tag (or google load).
Load TinyMCE's jQuery plugin, jquery.tinymce.js, with a script tag.
Document ready event fires; this is where you call .tinymce(settings) on your textareas. E.g.
$('textarea').tinymce({ script_url: '/tiny_mce/tiny_mce.js' })
Load tiny_mce.js this step is done for you by TinyMCE's jQuery plugin, but it could happen after the document ready event fires.
Sometimes you might really need to access window.tinymce, here's the safest way to do it:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
alert(tinymce);
}
});
TinyMCE will go so far as to create a tinymce.Editor object and execute the setup callback. None of the editor's events are triggered and the editor object created for the document is not added to tinymce.editors.
I also found that TinyMCE's ajax call was interfering with my .ajaxStop functions so I also used a setTimeout:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
setTimeout(function () {
$(document).ajaxStart(function(e) {/* stuff /});
$(document).ajaxStop(function(e) {/ stuff */});
}, 0);
}
});

Categories