Forum Moderators: coopster

Message Too Old, No Replies

call JavaScript from inside PHP script

Is it possible?

         

smallcompany

5:25 pm on Oct 6, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I’m trying to set goals within Google Analytics profile. The goal would be a click onto a link to PHP file which is used for outgoing link maintenance.

If I simply put the JavaScript code inside that PHP file, it breaks by complaining about that the header has already been loaded. PHP gets executed before JavaScript.

Is there a way to call that JavaScript part before PHP gets executed?

Thanks

eelixduppy

5:30 pm on Oct 6, 2008 (gmt 0)



You're going to need to use AJAX to do something like that. Take a look here for an example: [news.php.net...]

You might also want to take a look around the JavaScript/AJAX Forum for additional help.

sastro

6:02 am on Oct 7, 2008 (gmt 0)

10+ Year Member



Can you paste your code here?

smallcompany

6:55 am on Oct 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



AJAX

That seems to be bit complicated for me. Worse case scenario, I’ll use JavaScript based tracking of outgoing links.

code

<?php

if ($_GET['id'] == "link1") {$link = "http://www.outgoinglink.com";}

header("Location: $link");

include 'ga.php';

?>

In this case, a redirect works fine, but I’m not sure if ga.php is loading at all (have to wait for GA to pick up on it). If I put "include" onto the top, the script brakes as it complains about header being already loaded.

ga.php is a file that contains Google Analytics stuff only. I tried options like “print” or “echo”, but it would always brake.

I’ve spent most of my day in a search about how people handle this. I even came across a site offering PHP version of Google analytics code, but it was for some RSS purpose and I did not know if I could re-code it.
I also came across many JavaScript based solutions that present clicks onto outbound links as page views which was not bad, except that it was about having an extra JavaScript code in each page.

smallcompany

9:00 pm on Oct 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is there anything that could replace the "header" command, while doing the same job? Something that would allow “include” to happen before a redirect, or something that does not complain about “print” or “echo”.

I came across "redirectLocal". What's that? There is only one page of results on Google.

Thanks

Little_G

9:31 pm on Oct 7, 2008 (gmt 0)

10+ Year Member



Hi,

If you enable output buffering in php.ini then you can use header anywhere in the script.

Andrew

smallcompany

9:35 pm on Oct 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



output buffering

Thanks very much.

Now, are there any issues withy having it enabled?

Why would that be disabled by default?

Thanks

Little_G

9:43 pm on Oct 7, 2008 (gmt 0)

10+ Year Member



Hi,

It may use slightly more memory (whilst the script is executing) but it shouldn't be noticeable. I don't know of any other issues.

Andrew

smallcompany

10:42 pm on Oct 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks.

I came across some interesting stuff about that. For example, there is no need to do it on PHP.INI level, but script by script, by using ob_start(); accompanied with clean or flush at the end.

I’ll try that.

Thanks again.

andrewsmd

2:04 pm on Oct 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I call PHP with JavaScript all of the time. Here is some example code and you don't need to change anything the PHP.ini file.

I have a file called functions.php it looks something like this
<?php
Header("content-type: application/x-javascript");

//sets a hidden div to some passed in text if needed
//this is how you can output extra html in your page
//similar to setting a template with PHP but since
//all output has to be JS this is how i got around it
function echoDiv($name, $message){

echo("document.getElementById('".$name."').innerHTML =
'".$message."'");

}//echoDiv

//outputs message to a javascript alert box
function echoAlert($message){

echo "alert('$message')";

}//echoAlert
?>
Now I have a JS file called callFunc.js it looks like this
//<![CDATA[

// Define an error event handler
// this is just for errors you dont need all of this
// if you dont want it
function errorHandler(msg, url, line) {
var txt = "An error happened\n\n";
txt += "Error: " + msg + "\n";
txt += "URL: " + url + "\n";
txt += "Line: " + line + "\n";
txt += "Click OK to continue.\n\n";

alert(txt);
}

// Trigger error event handler when an error happens
window.onerror = errorHandler;

// Check if the user input is valid
function eventHandler (evnt) {
// this is for advanced DOM2 event handling
if (evnt.cancelable) {
evnt.preventDefault();
}

// This is for traditional and inline event handling
//return false;
}

//set up the events when the window is loaded
function setup(evnt) {

if (document.form.addEventListener)
document.form.addEventListener("submit", eventHandler, false);

else if (document.form.attachEvent)
document.form.attachEvent("onsubmit", eventHandler);

}//setup
window.onload=setup;


//]]>

//this is all you need it loads
//a php file and does some things
//to keep the page fresh
function loadFile(targetFile) {
var day = new Date();
var id = day.getTime();
targetFile += '?'+id;
var elem = document.createElement("script");
elem.setAttribute("src", targetFile);
document.getElementsByTagName("body")[0].appendChild(elem);
}

now in something like test.html do this
<html>
<body>
<input type = "checkbox" name = "checkbox" onclick="if(this.checked){loadFile('test.php')}">
<div id = "testHiddenDiv"></div>

Of course you could execute that JavaScript however you want
the nice thing about this is you can use the power of PHP to produce output and then just output it with JS

Now in test.php have this
<?php

require_once("functions.php");

//this is the alert box
echoAlert("testHiddenDiv", "Hello, you clicked the checkbox\\nWHOOOHOOO!");
echoDiv("<h1>Just showing some html</h1>");

?>

Do remember that all of your PHP output MUST be in the JS form.

smallcompany

7:16 pm on Oct 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



test.html

The point here is that I don't use tags like HTML or BODY as I’m not creating any output but doing a redirect only, via “header location”.

The whole script is really this:

<?php
if ($_GET['id'] == "site1") {$link = "http://www.site1.com";}
if ($_GET['id'] == "site2") {$link = "http://www.site2.com";}
header("Location: $link");
?>

That’s all. Now I need to trigger Google Analytics code, whenever the redirect is being called.

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-#*$!#*$!X-X");
pageTracker._trackPageview();
</script>

Will this JavaScript be inside those HTML tags, or just JavaScript like in .js file, or will it be inside PHP code, or called via include or something else, I don’t really care, as long as it does what is supposed to do.

So far, ob_start() and ob_end_flush() helped to overcome an error “Headers Already Sent”. Redirect works fine, but Google Analytics is not getting triggered.

I tried having it as inside “echo” or “print”, with properly escaped characters (single or double quotes), I tried to have it outside PHP tags, just like it would sit in regular HTML, but it is like it does not exists.

If I take out ob_start, I get an error about header.

By checking around the web, I saw that “output buffer” is something to go after. I’m just not sure why (in cases when I do not get an error) JavaScript does not get triggered.

Besides having it enabled on client side, are there any other conditions for JavaScript to work?

Thanks

[edited by: smallcompany at 7:18 pm (utc) on Oct. 8, 2008]