tracking clicks from edm to conversion - php

I need to track click-thru on my edm, and i need to see how many of these click-thru actually convert (within 30 days) at the end of the day.
So my idea is, on every link on the edm, i point them to my domain (siteA.com), where i set a cookie, then redirect them to the actual site where they initially clicked on (siteB.com).
The user then clicks on buy now and gets sent to the purchasing site (siteC.com).
On the purchase confirmation page, i call a script that resides on siteA.com, to grab the cookie that i set (if any) and logs the transaction.
So far, i managed to get to step 3, where it calls the script residing on siteA.com, but i am unable to get the value of the cookie that i set earlier. I know that it called the script, because the log file gets written to with the transaction details, but no cookie details. Am i using the wrong callback to the script on siteA.com? Or am i missing something totally?
So this is the code i'm using on the confirmation page:
<script type="text/javascript">
var adJsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + adJsHost + "siteA.com/tracker/tracking.php' type='text/javascript'%3E%3C/script%3E"));
logTransaction (orderValue , orderRef, merchantID, uid , htname, pixel, payoutCodes, offlineCode,checkOutDate,currencyCode);
</script>
on the tracking.php file, i have the following javascript code:
function logTransaction (orderValue , orderRef, merchantID, uid , htname, pixel, payoutCodes, offlineCode,checkOutDate,currencyCode)
{
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://siteA.com/tracker/confirmation.php?tranID="+uid+"&orderValue="+orderValue+"&currencyCode="+currencyCode,true);
xmlhttp.send();
}
and finally, this is what i have on the confirmation.php
if (isset($_COOKIE["myedm"])) {
$cookie_array = explode(",", $_COOKIE["myedm"]);
$mc_cid = $cookie_array[0];
$mc_eid = $cookie_array[1];
$numberofvisits = $cookie_array[2];
}
$tranID = $_GET['tranID'];
$orderValue = $_GET['orderValue'];
$currencyCode = $_GET['currencyCode'];
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "\n tranID:".$tranID;
$current .= "\n currencyCode:".$currencyCode;
$current .= "\n orderValue:".$orderValue;
$current .= "\n mc_cid:".$mc_cid;
$current .= "\n mc_eid:".$mc_eid;
$current .= "\n numberofvisits:".$numberofvisits;
// Write the contents back to the file
file_put_contents($file, $current);

Update:
I fixed the problem.. kind of..
changed the javascript calling the file to using a img pix, i.e.
<img src="http://siteA.com/tracker/confirmation.php?tranID=123&orderValue=150&currencyCode=USD">
it works! but only in firefox n chrome. In IE, doesn't seem to want to set the cookie even..

Related

Passing a variable from javascript using $_POST

I am trying to pass a variable from a javascript function to my php file. All I do is extract the user_name from a cookie in javascript and then use AJAX to $_POST the variable to my php file for processing. I do not use a form to submit the POST variable which I have done in the past.
The problem is my $_POST array is not getting passed to the php file. I've looked here and looked at several other suggestions but none work. Do you have to submit the $_POST variable via an html form? I dont think so but maybe I'm wrong. Here is the code:
Javascript -
function clearDoneItems() {
var user_name = getNameFromCookie();
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert(user_name);
xmlhttp.open("POST","todolist/clear_done_items.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(user_name);
displayHomeInformation(user_name);
}
PHP -
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Clear Done Items</title>
</head>
<body>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
print_r($_POST);
$xml_name=$_POST['user_name'];
$xml_file = $xml_name . ".xml";
echo $xml_file;
/* Here we will use the The DOMDocument class functions to delete
the text nodes.
Format XML to save indented tree rather than one line */
$domxml = new DOMDocument('1.0');
if ($domxml->load('$xml_file') === TRUE) {
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
// Start Delete process of node
echo "<br>";
$xpath = new DOMXPath($domxml);
// Here we use the The DOMXPath class function evaluate to do the heavy lifting.
foreach ($xpath->evaluate('//doneitems/item') as $node) {
$node->parentNode->removeChild($node);
}
//Save XML to file - remove this and following line if save not desired
$domxml->save('alan.xml');
echo "<strong>XML Document updated.</strong>";
}
else {
echo " <strong>Error in loading XML file:</strong>";
echo "<br>";
print_r(error_get_last());
}
?>
</body>
</html>
Errors on php page:
Notice: Undefined index: user_name in /var/www/bb/todolist/clear_done_items.php on line 16
0
Warning: DOMDocument::load(): I/O warning : failed to load external entity "/var/www/bb/todolist/$xml_file" in /var/www/bb/todolist/clear_done_items.php on line 24
Sorry for the delay in responding. I just wanted to post how I solved issue. I will have to revisit using the $_POST array with AJAX cause I was never able to pass a variable thru it.
Javascript:
// Clear Done Items Function
function clear_done_items()
{
var xmlhttp;
var temp = document.getElementById("list_section");
var temp_list_name = temp.innerHTML;
var str_len = temp_list_name.length;
var list_name = temp_list_name.slice(17,str_len);
var user_name = getNameFromCookie();
if (user_name == list_name) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","todolist/clear_done_items.php",true);
xmlhttp.send();
} else {
alert("Warning: You Must be Logged in as this User, " + list_name + ", to Delete the Completed Items List");
}
}
and php:
<?php
$xml_cookie = $_COOKIE['user'];
$xml_file_name = $xml_cookie . ".xml";
/* Here we will use the The DOMDocument class functions to delete
the text nodes.*/
//Format XML to save indented tree rather than one line
$domxml = new DOMDocument('1.0');
if ($domxml->load($xml_file_name) === TRUE) {
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
// Start Delete process of node
echo "<br>";
$xpath = new DOMXPath($domxml);
// Here we use the The DOMXPath class function evaluate to do the heavy lifting.
foreach ($xpath->evaluate('//doneitems/item') as $node) {
$node->parentNode->removeChild($node);
}
//Save XML to file - remove this and following line if save not desired
$domxml->save($xml_file_name);
echo "<strong>XML Document updated.</strong>";
}
else {
echo " <strong>Error in loading XML file:</strong>";
echo "<br>";
print_r(error_get_last());
}
?>
so basically I'm using a cookie to get the user_name variable to php to process from the main page.

Overwrite session variable using ajax

I have created an YouTube search engine that sends video id, title etc. using session. I have created buttons with unique ids for each of them, onclicking which a page is called via ajax and the session is generated using the unique id for that button.
The javascript code is like follows:
<script type="text/javascript">
function loadXMLSession(videoid, videotitle) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GenerateDownloadSession.php?videoid=" + videoid + "&videotitle=" + videotitle, true);
xmlhttp.send();
//strip off spaces and embed dashes - clean urls
var downloadtitle = videotitle;
downloadtitle = downloadtitle.toLowerCase();
downloadtitle = downloadtitle.replace("-"," ");//strip off dashes with spaces
downloadtitle = downloadtitle.replace(/ +(?= )/g,'');//replace multiple spaces with one space
downloadtitle = downloadtitle.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');//strip off all special characters from video title
downloadtitle = downloadtitle.replace(/ /g,"-");//replace spaces with dashes
downloadtitle = downloadtitle.replace(/-+$|(-)+/g, '$1');//replace multiple dashes with single dash
var url = window.location.hostname;
url = "/development"//only for development phase
url = url+"/download/"+downloadtitle+".html";
window.location=url;
}
</script>
The download buttons are coded as follows:
echo "<button id=\"downloadbtn\" class=\"btn\" value = \"" . $YouTubeVideoID . "\" onclick=\"loadXMLSession(this.value,'" . $VideoContent['6'] . "')\"><img src=\"" . $HostURLRedirect . "/img/Arrow-Down-icon.png\" alt=\"download\" /> Download</button> ";
The php page called by ajax has simple session creation:
session_start();
$videoid = $_GET['videoid'];
$videotitle = $_GET['videotitle'];
$_SESSION['DownloadID'] = $videoid;
$_SESSION['DownloadTitle'] = $videotitle;
$_SESSION['DownloadType'] = "Download";
The problem that I am having is, when I click on any of the download button for the first time after opening the browser, it is working well. But when I search again, it is returning the previous session values. I am calling the session function through ajax and passing values to it. And, it should overwrite the session values. But in this case, it is not overwriting the values. How can I overcome this issue? Any suggestions?
At
xmlhttp.open("GET", "GenerateDownloadSession.php?videoid=" + videoid + "&videotitle=" + videotitle, true);
xmlhttp.send();
you are doing an asynchronous Request, which means, that the javascript continues after sending the request, not waiting for it to complete. Most likely it will hit your redirect of your current page to the download before the call could change the Session data.
Solution 1.) Make the script synchronous by setting the last parameter to false.
Solution 2.) Move your forward logic into the onreadystatechange callback function.
on a side node: why using ajax for this? you could simple pass the parameters appended to the url when forwarding...?
Do you have the GET-Values set when requesting your Script?
Use your Firebug to check what is answered by the PHP-Script. (Network -> you will see the requested file being loaded when your Ajax Request is being started).
you should change the location of you page once you get the ajax response:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var downloadtitle = videotitle;
downloadtitle = downloadtitle.toLowerCase();
downloadtitle = downloadtitle.replace("-"," ");//strip off dashes with spaces
downloadtitle = downloadtitle.replace(/ +(?= )/g,'');//replace multiple spaces with one space
downloadtitle = downloadtitle.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');//strip off all special characters from video title
downloadtitle = downloadtitle.replace(/ /g,"-");//replace spaces with dashes
downloadtitle = downloadtitle.replace(/-+$|(-)+/g, '$1');//replace multiple dashes with single dash
var url = window.location.hostname;
url = "/development"//only for development phase
url = url+"/download/"+downloadtitle+".html";
window.location=url;
}
}
But I most be honest, I dont see the point of using ajax and then changing the location of the actual page.
Maybe you should start the download in another window?

Load external page into div after clicking on item from php list

I know, I know. From the title up above, you are probably wondering what in in the world I am asking. Let me try and break this down a little easier because I am stuck and cannot figure this out. So here goes..............
I have a place on my site where a user can look at a list of news items that have been posted. All of the news items are listed in a MYSQL database and is retrieved and displayed on the page using PhP, like this:
$sql_list = "SELECT * FROM LatestMusic WHERE active = 'y' ORDER BY lm_id DESC";
$sql_list_result = mysql_query($sql_list,$connection) or die ('Could not select the List of Latest Music Entries');
$bgc = "FFC6C6";
while($list_data = mysql_fetch_array($sql_list_result)){
if ($bgc == "FFC6C6") {
$bgc = "FFFFFF";
} else {
$bgc = "FFC6C6";
}
print "<tr bgcolor=\"#" .$bgc. "\">";
print "<td align=\"center\" width=\"44\">";
print "<img src=\"/images/b_edit.png\" border=\"0\">";
print "</td>";
print "<td align=\"center\" width=\"63\">";
print "<img src=\"/images/b_drop.png\" border=\"0\">";
print "</td>";
print "<td align=\"left\" style=\"padding-left: 15px;\">";
echo $list_data[1];
print "</td>";
print "</tr>";
}
That part I get. From there, when the user click on anyone of the entries listed from the database, I need an external PHP page to load inside of a DIV on the same page without loading. I am using this coding in the header on the same page in order to achieve such a task:
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "YSMhome_LMeditform.php", true);
xmlhttp.send();
}
</script>
I can get the external page to load just fine into the DIV without the page reloading. The problem I'm having is this: The page that loads needs to be a form with form fields. When a user clicks on an entry in the list from the database, I need to pass a variable from the list (letting me know which entry they clicked on) into the external page that is loading in the DIV so that I can pre-populate the form fields with the data being sent. That is the part I cannot figure out.
If anyone can assist me with this, it would be greatly appreciated. I am new to AJAX (this is my first attempt with it), but I am willing to learn what I need to in order to get this to work.
When you call your ajax function, you need to pass it the relevant information. In your example, you should change:
onclick=\"loadXMLDoc()\"
to something like (assuming that $list_data[0] is an integer for simplicity):
onclick=\"loadXMLDoc({$list_data[0]})\"
Then in javascript, your function definition would look something like:
function loadXMLDoc(id)
and later on, you could change the url that is called to something like:
"YSMhome_LMeditform.php?id=" + id
Then you would have the ID available in "YSMhome_LMeditform.php as $_GET['id'].

Ajax and/or PHP error

I am using AJAX along with PHP to communicate the time a visitor spends on a page to the server where the PHP scripts writes the time spent along with other details to a text file. The AJAX script is unable to call the php script and hence the visitor details are not being logged
<script type="text/javascript">
var startTime = new Date(); //Start the clock!
window.onbeforeunload = function() //When the user leaves the page(closes the window/tab, clicks a link)...
{
var endTime = new Date(); //Get the current time.
var timeSpent = (endTime - startTime); //Find out how long it's been.
var xmlhttp; //Make a variable for a new ajax request.
if (window.XMLHttpRequest) //If it's a decent browser...
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest(); //Open a new ajax request.
}
else //If it's a bad browser...
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //Open a different type of ajax call.
}
xmlhttp.open("GET","ajaxphp.php?time="+timeSpent,false); //The false at the end tells ajax to use a synchronous call which wont be severed by the user leaving.
xmlhttp.send(); //Send the request and don't wait for a response.
}
</script>
This is the AJAX script
The PHP script is given below too :
<?php
$time=$_GET["time"];
$countfile = "counter.txt";
// location of site statistics.
$statsfile = "stats.txt";
// checks whether the file exist, if not then server will create it.
if (file_exists($countfile)) {
// open the counter hit file.
$fp = fopen($countfile, "r");
// reads the counter hit file and gets the size of the file.
$output = fread($fp, filesize($countfile));
// close the counter hit file.
fclose($fp);
// get the integer value of the variable.
$count = intval($output);
}
// if file is doesn't exist, the server will create the counter hit file and gives a value of zero.
else {
$count = 0;
}
// showcount function starts here.
function ShowCount() {
// declares the global variables.
global $ShowCount, $countfile, $statsfile, $count,$time;
// get the current month.
$month = date('m');
// get the current day.
$day = date('d');
// get the current year.
$year = date('Y');
// get the current hour.
$hour = date('G');
// get the current minute.
$minute = date('i');
// get the current second.
$second = date('s');
// this is the date used in the stats file
$date = "$month/$day/$year $hour:$minute:$second";
// this is the remote IP address of the user.
$remoteip = getenv("REMOTE_ADDR");
// some of the browser details of the user.
$otherinfo = getenv("HTTP_USER_AGENT");
// retrieve the last URL where the user visited before visiting the current file.
$ref = getenv("HTTP_REFERER");
// open the statistics file.
$fp = fopen($statsfile, "a");
// put the given data into the statistics file.
fputs($fp, "Remote Address: $remoteip | ");
fputs($fp, "Information: $otherinfo | ");
fputs($fp, "Date: $date | ");
fputs($fp, "Referer: $ref\n");
fputs($fp, "Time Spent: $time | ")
// close the statistics file.
fclose($fp);
// adds 1 count to the counter hit file.
$count++;
// open the counter hit file.
$fp = fopen($countfile, "w");
// write at the counter hit file.
// if the value is 34, it will be changed to 35.
fwrite($fp, $count);
// close the counter hit file.
fclose($fp);
// showcount variable is equal to count variable.
$ShowCount = $count;
// return the value of the count variable into showcount variable.
return $ShowCount;
}
// display the value in the counter hits file.
echo showcount(), " visits";
?>
Try the following:
Access the url ajaxphp.php?time=123456 directly with your web browser and note what happens
Use an onclick handler on a button that activates the ajax call and note what happens
Use jquery instead for the ajax and note what happens
I'm sure one of these will give you more clues to why your current setup fails.

Why is this AJAX function not working properly?

I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)

Categories