Overwrite session variable using ajax - php

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?

Related

Send string to php server and use it

Im trying to send a string to a php server, but for some reason, Im not able to read the string on the server... I tried many ways to type it well but it seems like I never got the correct syntax. Anyone have clues?
var command="";
if(document.getElementById("Text_1").value != "" && document.getElementById("Text_2").value != "")
{
command += " " + document.getElementById("Text_1").value + " " + document.getElementById("Text_2").value;
}
alert(command);
xmlhttp.open("POST", "server.php", false);
xmlhttp.setRequestHeader('info', command)
//TRIED xmlhttp.setRequestHeader("info, command")
//TRIED xmlhttp.setRequestHeader('info', 'command')
//TRIED many others sketchy things...
xmlhttp.send();
//TRIED xmlhttp.send(command);
var output = xmlhttp.responseText;
On php server :
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
echo json_encode($parameter);
?>
For them wondering, if I hardcode $parameter with a right string, it works, so the executable isn't the problem. The server just cant get the value of the string in $_POST.
setRequestHeader is used to set headers on the request. Things like Content-type and Content-length.
You need to pass the data to send(). For $_POST to work, they need to be in key=val&vey2=val2 format. Actually, in newer browsers, you can use FormData.
xmlhttp.open("POST", "server.php", false);
// To emulate a `<form>` POST
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// To get the response, you need to set a callback
xmlhttp.onreadystatechange = function(){
// readyState 4 = complete
// status = 200 OK
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var output = xmlhttp.responseText;
}
};
// Create the Form Data
var params = new FormData;
params.append('command', command);
xmlhttp.send(params);
P.S. You should run escapeshellarg() before running your command. This could be worse than just SQL injection if people can run arbitrary commands on your server.
<?php
$parameter = escapeshellarg($_POST['command']);
$output = exec("someexecutable.exe $parameter");
?>
P.P.S. escapeshellarg() will make your command treat the entire $_POST['command'] string as one parameter. If you don't want that, then you'll need to POST an array from your JavaScript.
// Create the Form Data
var params = new FormData;
params.append('command[]', document.getElementById("Text_1").value);
params.append('command[]', document.getElementById("Text_2").value);
xmlhttp.send(params);
Now $_POST['command'] will be an array, so you'll have to run the command like so:
<?php
$parameters = array_map('escapeshellarg', $_POST['command']);
$output = exec("someexecutable.exe ".implode(' ', $parameters));
?>

Loading content on tab click

I recently found a cool tabbed content page, where when you click on the tabs they show content http://codepen.io/unasAquila/pen/nDjgI What I discovered was, that these tabs were preloaded once you enter the page, rather than being loaded as the tabs are clicked on. I was wondering if it is possible to make it to where the content loads as you click on the tab. For example, If I have a PHP Query statement where I want to load information such as this:
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
while($row = mysqli_fetch_array($query3))
{
echo "$row[name]
}
How would I make it to where the content is only loaded once the tab is clicked on?
It can be done using AJAX. Simply put, AJAX is a technology that allows sending requests to the back-end when an event triggers on the front-end.
You could make the following:
In your HTML:
<!-- Change myTabId to whatever id you want to send to the server side -->
<element onclick="loadTab(myTabId)">my tab</element>
In your JS:
// Will be executed on tab click
function loadTab(tabId) {
var xmlhttp = new XMLHttpRequest();
// Define a handler for what to do when a reply arrives from the server
// This function will not be executed on tab click
xmlhttp.onreadystatechange = function() {
// What to do with server response goes inside this if block
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Change the content of the element with id "myTabContent" to the server reply
document.getElementById("myTabContent").innerHTML = xmlhttp.responseText;
}
}
// Opens a connection to "myServerSideScript.php" on the server
xmlhttp.open("GET", "myServerSideScript.php?id=" + tabId, true);
xmlhttp.send();
}
Now you need to create myServerSideScript.php on the server root with a content similar to the following:
$id = $GET[id]; //The GET parameter we sent with AJAX
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
$response = "";
while ($row = mysqli_fetch_array($query3)){
$response .= $row[name];
}
// To return a reply you just need to print it
// And it will be assigned to xmlhttp.responseText on the client side
echo $response;
You can learn more about AJAX here

Passing php variable to xmlhttp.responseText

Haven't found this exact situation on here, so I figured I'd ask. I have some JavaScript that, using AJAX, is attempting to call a PHP file, execute the PHP script, and return a concatenated PHP variable through xmlhttp.responseText, then alert that response.
JS
function queryDB() {
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)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php/location.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP
<?php
$con = mysql_connect("<THIS DATA HIDDEN FOR SECURITY PURPOSES, IT IS CORRECT");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gpstracks", $con);
$bus = $_GET['bus'];
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
$latlon = mysql_query($query);
while ($row = mysql_fetch_array($latlon, MYSQL_ASSOC)) {
$lat = $row['lat'];
$lon = $row['lon'];
}
$result = $lat . ", " . $lon;
echo $result;
mysql_close($con);
?>
Yes, I know that mysql_ has been replaced by mysqli_, I'll deal with that later. When I execute the PHP on its own (using a form submit) - it displays the correct values from the table, but when I alert the xmlhttp.responseText - I only get the comma and space - no passed variables. Any idea what I'm doing wrong? Help is much appreciated.
Sidenote: I know the preferred method for AJAX calls these days is jQuery - but a component of the page this JavaScript is on doesn't function when I use jQuery.
when I alert the xmlhttp.responseText - I only get the comma and space - no passed variables
You're not performing your GET properly; in your JavaScript you have
xmlhttp.open("GET","php/location.php",true);
i.e. you performed a GET request without a URI query string.
In your PHP you have
$bus = $_GET['bus'];
i.e. you're GETting this data from the URI query string, except none was passed, so this will be empty, so
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
doesn't work as expected.
You really wanted to do something like
xmlhttp.open(
"GET",
"php/location.php?bus="+window.encodeURIComponent(foobar),
true
); // foobar your value for `bus`
Further, you'll need to do some server-side sanitisation of $bus, as it stands you're open to SQL injection.
As you send request by GET method, you need to manually add the parameter bus to the URL. So, rewrite
xmlhttp.open("GET","php/location.php",true);
to
xmlhttp.open("GET","php/location.php?bus=value",true);
You should pass "bus" in on the PHP file URL.

tracking clicks from edm to conversion

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..

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