I'm trying to create a script that pings my Minecraft server to check how many players are online, but for some reason question marks are getting displayed and it makes the whole website look like crap. Here's my PHP file.
<script>
function setOnline(online,max) {
var on = online;
var mx = max;
var main = document.getElementById('status_main');
main.className = "panel panel-success server-status";
var title = document.getElementById('status_title');
title.innerHTML = "Online";
var body = document.getElementById('status_body');
body.innerHTML = on + "/" + mx + " Players Online";
}
</script>
<script>
function setOffline() {
var bar = document.getElementById('status');
bar.className = "panel panel-danger server-status";
bar.text = "Offline";
}
</script>
<?php
$host = "localhost"; //IP/host of Minecraft server
$port = 25565; //Minecraft server port, not query port
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //Create the socket
$connected = socket_connect($socket, $host, $port); //Try and connect using the info provided above
if (!$connected)
die(); //No connection could be established
socket_send($socket, "\xFE\x01", 2, 0); //Send the server list ping request (two bytes)
$retVal = socket_recv($socket, &$data, 1024, 0); //Get the info and store it in $data
socket_close($socket); //Close socket
if ($retVal != false && substr($data, 0, 1) == "\xFF") //Ensure we're getting a kick message as expected
{
$data = substr($data, 9); //Remove packet, length and starting characters
$data = explode("\x00\x00", $data); //0000 separated info
$protocolVersion = $data[0]; //Get it all into separate variables
$serverVersion = $data[1];
$motd = $data[2];
$playersOnline = $data[3];
$playersMax = $data[4];
echo ("<script>setOnline('$playersOnline','$playersMax');</script>");
}
else
{
die();
}
?>
Here's what the result looks like when it's called:
http://cl.ly/image/3o2f3P121q0m
How can I get rid of the question marks?
This is likely a charset issue. The information is not being presented in the way that it was encoded.
You can var_dump $data to see its Content-Type.
Here is just a hypothesis: the actual encoding is ISO-8859-1, but it is being interpreted as UTF-8 (or UTF-16).
To make the browser use the correct encoding, you can add an HTTP header:
header("Content-Type: text/plain; charset=ISO-8859-1");
or use a meta tag.
Related
I am setting up a Server Sent Event connection between my instant messaging page and my sse page in php. But firefox tells me that it could not connect to the server. I followed an article telling me to put in php.ini : output_buffering = Off and zlib.output_compression = Off.
Then I arrived at this result by adding my personal code so that the code does what I want:
client code:
<script type="text/javascript">
var eventSource = new EventSource("includes/load_chat.php");
eventSource.onmessage = function(event) {
document.getElementById("message").innerHTML += event.data;
console.log('messsssage!!!!')
};
</script>
server code :
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include 'database_message.php';
global $msg_bdd;
$from = '2';
$to = '1';
$id_discution = "ezdhnijkezd&ézuoijde_hjé_àe'dzunbfezd";
// test values
$dmd_last_id_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id ORDER BY creation_date DESC');
$dmd_last_id_msg->execute([
'id' => $id_discution
]);
while($message = $dmd_last_id_msg->fetch()){
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
break;
}
while (true) {
if(connection_aborted()) exit();
$dmd_if_new_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id AND creation_date >= :last_creation ORDER BY creation_date');
$dmd_if_new_msg->execute([
'id' => $id_discution,
'last_creation' => $last_msg_date
]);
$data = 'data: ';
echo $data;
while($message = $dmd_if_new_msg->fetch()){
if(in_array($message['id'],$last_msg_id)){}
else{
if($message['user'] == $from){$id_div = "from";}
elseif($message['user'] == $to){$id_div = "to";}
$data = '<div class="message" id="' .$id_div. '"><p>' .$message['message']. '</p></div><br><br><br>';
$data = htmlspecialchars($data);
echo $data;
if ($message['creation_date'] > $last_msg_date) {
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
}
elseif($message['creation_date'] = $last_msg_date){
array_push($last_msg_id, $message['id']);
}
}
}
flush();
sleep(1);
}
?>
Where can the problem come from ? client ? server ? What is the problem? Thanks for reading
I'm working on a bidding system. I have the timer to read from the database and display a message when it reaches 00:00. Now i want to manipulate the timer in such a way that when it is <= 10secs(00:00:00:10), and a button is clicked then it should reset back to 00:00:00:10 and continue. The timer display is in day, hour, minute, and seconds.
Here is the javascript code
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);
Here is the php code
<body>
<?php
$mysqli = new mysqli("localhost","root","", "auction");
if (!$mysqli)
{
die('Could not connect: ' . mysql_error());
}
else{
$sql = "INSERT INTO bids (id, description, closing_date) VALUES
(NULL, 'Acer Aspire 4736', '2011-10-22 18:50:26')";
}
$result = $mysqli->query("SELECT * FROM bids WHERE id = 1");
$row = mysqli_num_rows($result);
if ($row == 0)
{
die('No record found.');
}
$row = $result->fetch_array();
echo "Description: " . $row[1] . "<br />";
$closedate = date_format(date_create($row[2]), 'm/d/Y H:i:s');
echo "Closing Date: " . $closedate;
?>
<p>Time Left:
</p>
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "blue";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown.js"></script>
</body>
here is the code for the display in html
<?php
$A=0;
if ($A%4 ==0):;?>
<?php
while ($auction=$result->fetch_assoc()):;?>
<div class = "grid ">
<h4 class="c-head"><?=$auction['item_name']?></h4>
<img src='<?=$auction['item_image']?>' class="img-responsive">
<span class="timer">
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%%, %%H%%:%%M%%:%%S%%";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown\countdown.js">
</script>
</span>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="digit" class="form-control"
name="duration">
<span class="input-group-btn "><button class="btn btn-
primary c-button" type="button" name="bid">Bid now!</button></span>
</div>
</div>
<?php endwhile; $A++; endif;?>
I'm novice in php...just started learning it a couple of weeks ago. Your time is greatly appreciated.
I wroted that to help your start. I haven't currently a dev environment under hands so I didn't run this code,.
All the php files have to be put in the same directory to communicate
This file when required should allow you to communicate with your database. Moreover I used PDO that is good practice when requesting database to avoid SQL injections.
Please check the php documentation http://php.net/manual/fr/class.pdo.php
// database_connection.php
$host = 'localhost';
$user = 'root'; // Bad idea to user root user ^^'
$password = 'yourpassword';
$dbname = 'auction';
try {
$dsn = sprintf('mysql:host=%s;dbname=%s', $host, $dbname);
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // I active errors, if you are a beginner that'll help you, comment this in prod env
// I use PDO to avoid SQL injections, this line open a mysql connection, check the documentation
$connection = new PDO($dsn, $user, $password, $pdo_options);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
exit;
}
You have to implement a HTML POST form with a description input which will submit to this PHP file
This file handle the creation of a bid
// addBid.php
// You have to implement a HTLM POST form with the needed fields which will submit to this PHP file
// The url yourdomain.fr/addBid.php
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$description = isset($_POST['description']) ? $_POST['description'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended description isn't valid
if(empty($description) || !is_string($description)) {
redirectTo($urlListing);
}
// You should do some verification on the string that send the user, it can be malicious html/javascript code, XSS attack
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'INSERT INTO bids(description, closing_date) VALUES(":description", ":closing_date")';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':description' => $description
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the bid is created
$urlListing .= '?created=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
This third file handle the update of bid that is in the database
// updateBid.php
// The url yourdomain.fr/updateBid.php?bidId=6 will update the bid with id 6 into database
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$bidId = isset($_GET['bidId']) ? $_GET['bidId'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended bidId isn't valid
if(empty($bidId) || !is_numeric($bidId)) {
redirectTo($urlListing);
}
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'UPDATE bids SET closing_date = ":dateToModify" WHERE id = :id';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':id' => $bidId
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the $bidId is present in database
$urlListing .= '?updated=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
You should do some tutorials learn PHP and MYSQL, that'll help you a lot :)
Moreover when you use a PHP framework it is more difficult at the start but after that you'll learn a lot reading code. And the framework help you to stay in the "good practices", it very easy in php to do some shit code.
I hope I didn't so many syntax or logic error but I know that the stackoverflow community will correct me if needed
Sorry for my english !!
An up vote would be greatly appreciated :)
Building a messaging system for my site and i have been stuck for days. I have this PHP link
<a href='user_msg.php?hash=$hash'>$name</a>
When you click on the link, it takes you to a page where you can send message to a user you've connected to (this connection is binded by the $hash)
in the page for sending the message, i hid the $hash in and hidden input value="$hash" and it sends the message to row in database with the $hash with the following scripts (They have no issue and work fine)
var msg_area = $('.msg_area');
msg_area.scrollTop(msg_area.prop("scrollHeight"));
$('#send_rep').submit(function (e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');
var posting = $.post(url, {rep_msg: $('#rep_msg').val(), hash: $('#hash').val()});
posting.done(function (data) {
alert('success');
});
});
PHP script to send
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['rep_msg']) && !empty($_POST['rep_msg']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_GET['hash'];
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['rep_msg'];
$hash = $_POST['hash'];
$rsql = <<<EOF
INSERT INTO messager (message, group_hash, from_id) VALUES('$rep_msg', '$hash', '$my_id');
EOF;
$rret = $db->exec($rsql);
$ursql = <<<EOF
SELECT * FROM User WHERE ID = '$my_id';
EOF;
$urret = $db->query($ursql);
while ($urrow = $urret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urrow['fname'];
$from_img = $urrow['image'];
header('Location: user_msg.php?hash=' . $hash);
}
}
The above Ajax Request and php script work fone to sedn the messages to database.
The issue not is getting the messages from database
This is the script i am currently using (not working)
PHP script to get message
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_GET['hash']) && !empty($_GET['hash']))
{
$hash = (int)$_GET['hash'];
$us_id = $_SESSION['log_id'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hash';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM User WHERE ID = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['image'];
if ($from_id != $_SESSION['log_id']) {
echo "
<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><div class='from_txt'><p>$messages</p></div></div>";
} else {
echo "
<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><div class='rep_txt'><p>$messages</p></div></div>";
}
}
echo "<input style='display: none' type='text' class='hash' name='hash' value='$hash' id='hash'>";
}
}
Ajax Request
setInterval(function() {
$('.msg_area').load("get_msg.php");
}, 2000);
But the get is not working. I suspect fro some reason, its not getting the $hash. Please is there a solution to this or am i trying something impossible.
Any help would be appreciated. If more info is needed please ask. Thanks in advance
Maybe $hash = (int)$_GET['hash']; would be $hash = (int)$_POST['hash'];
And you have more than just one $_GET...
In your ajax request you are using POST so you will need to get the hash with the POST as well: if (isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_POST['hash'];
Using '' in PHP indicates the actual string you are writing.
If you want to use a PHP variable in a string you should use "", so try changing $name
Check this for more info:
http://php.net/manual/en/language.types.string.php
Then, how do you hide your hash in the input?
You could use <input value="$_GET['hash']" ... />
In the script to send , does it enter the if? Try adding statements to see if SQL returns any error.
Hope this helps.
Answer to the question was to create a PHP SESSION for the $hash($_SESSION['hash'] = $hash) and to use this session all over the site with session_start().
I have a reporting website that I use DataTables Server Side Processing on. Everything works great except that I need to be able to export the whole data set and not just the part that is showing on the screen. I have reports that have 10,000+ rows and 65+ columns so showing the whole report on the page is out of the question (would take more than 5 minutes and then time out). I've gotten really close to an answer, I think, but need help getting the rest of the way. Here's what I've got:
I'm collecting the data that I need sending it to a file that uses PHPExcel libraries to export an Excel file.
When I navigate to the file (ExportAllToExcel.php) it works fine, but when I use a button to send the data to the file there is no download. Here's what I've got going right now:
$.fn.dataTable.ext.buttons.export =
{
className: 'buttons-alert',
id: 'ExportButton',
text: "Export All Test III",
action: function (e, dt, node, config)
{
var SearchData = dt.rows({ filter: 'applied' }).data();
var OrderData = dt.order();
var NumRow = SearchData.length;
var SearchData2 = [];
for (j = 0; j < NumRow; j++)
{
var NewSearchData = SearchData[j];
for (i = 0; i < NewSearchData.length; i++)
{
NewSearchData[i] = NewSearchData[i].replace("<div class='Scrollable'>", "");
NewSearchData[i] = NewSearchData[i].replace("</div>", "");
}
SearchData2.push([NewSearchData]);
}
for (i = 0; i < SearchData2.length; i++)
{
for (j = 0; j < SearchData2[i].length; j++ )
{
SearchData2[i][j] = SearchData2[i][j].join('::');
}
}
SearchData2 = SearchData2.join("%%");
//var SendPageData = new XMLHttpRequest();
//SendPageData.open("POST", "./ExportAllToExcel.php", true);
//SendPageData.send('{NumRow=' + NumRow + '},{SearchData=' + SearchData2 + '}');
$.post('./ExportAllToExcel.php',{SearchData: SearchData2,NumRow: NumRow});
window.location.href = './ExportAllToExcel.php';
}
};
This doesn't work. The $.POST sends the data and gets a response, but does not export the file.
The Window.location goes to the file and exports to Excel but doesn't have the data from $_POST so the file only has headers.
And the SendPageData does the same as the $.POST sends the data and gets a response, but doesn't create the file.
And here's the ExportAllToExcel.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/dev/Location/Helper/PageName.php'; //Pulls the Page name and Table name and returns the $SQLTableName, $TableName, $Title, $Page and $HeadingDesc
include $_SERVER['DOCUMENT_ROOT'].'/dev/Location/DBConn.php'; //DB connection info
$headings = array(); //Create the empty array for use later and so that it won't throw an error if not assinged later
$hsql = "select Headings from TableHeadings where TableName = '$TableName' order by Id"; //Get all the column headers from the TableHeadings table in SQL
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$CountHeadings = count($rHeadings); //Count how many columns that there will be
$tsqlHeadings = '';
$ColumnHeader = array();
for ($row = 0; $row < $CountHeadings; $row++)
{
$headings[$row] = $rHeadings[$row]["Headings"]; //fill the array of column headings for use in creating the DataTable
}
print_r($headings);
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
// Add some data
$ColumnArray = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
//$HeadingArray = array('Year','Quater','Country','Sales');
$HeadingArray = $headings;
$primaryKey = 'id';
$table = $SQLTableName;
$request = $_POST;
$dataArray = array();
$dataArraystr = explode('%%',$_POST['SearchData']);
foreach($dataArraystr as $ArrayStr)
{
$dataArray[] = explode('::',$ArrayStr);
}
// Include PHPExcel
require_once dirname(__FILE__) . './Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Michael McNair")
->setLastModifiedBy("Michael McNair")
->setTitle($TableName)
->setSubject($TableName)
->setDescription("Report for " .$TableName. " using PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php " . $TableName)
->setCategory("Report Export File");
$objPHPExcel->getActiveSheet()->fromArray($HeadingArray, NULL, 'A1');
$objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A2');
$CountOfArray = count($HeadingArray);
// Set title row bold
$objPHPExcel->getActiveSheet()->getStyle('A1:' .$ColumnArray[$CountOfArray-1]. '1')->getFont()->setBold(true);
// Set autofilter
// Always include the complete filter range!
// Excel does support setting only the caption
// row, but that's not a best practise...
$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('SimpleTest');
// Add a second sheet, but infront of the existing sheet
//$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel,'New Worksheet');
//$objPHPExcel->addSheet($myWorkSheet,0);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="ExportAllToExcelTest.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
///$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
ob_clean();
$objWriter->save('php://output');
?>
I have fixed the problem. This is the button now:
$.fn.dataTable.ext.buttons.export =
{
className: 'buttons-alert',
id: 'ExportButton',
text: "Export All To Excel",
action: function (e, dt, node, config)
{
window.location.href = './ServerSide.php?ExportToExcel=Yes';
}
};
I use just the one $_GET and send that to my ServerSide.php file, the same file that gets the data for the browser, to begin with. There I now check for that and use my KeepPost.php file to keep the filtering and sorting that the user has placed on the report:
<?php
if( isset($_POST['draw']))
{
include 'DBConn.php';
//echo "Here";
//print_r($_POST);
$KeepPost = $_POST;
$KeepPost['length'] = -1;
$PostKept = serialize($KeepPost);
$TSQL = "UPDATE PostKept set Value = '" .$PostKept. "'";
$sth = $conn->prepare($TSQL);
//print_r($sth);
$sth->execute();
}
?>
Then in ServerSide.php I check for the $_GET['ExportToExcel']:
if (isset($_GET['ExportToExcel']) && $_GET['ExportToExcel'] == 'Yes')
{
$GetSQL = "Select Value from PostKept";
$KeepResult = $conn->query($GetSQL);
$KeepResults = $KeepResult->fetchALL(PDO::FETCH_ASSOC);
//print_r($KeepResults);
error_log(date("Y/m/d h:i:sa")." KeepResults: " .$KeepResults[0]['Value']. "\n",3,"C:\Temp\LogPHP.txt");
//findSerializeError($_COOKIE['KeepPost']);
//print_r($_COOKIE);
$request = unserialize($KeepResults[0]['Value']);
//echo "<br>Request: "; print_r($request);
$DataReturn = json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader,1));
//echo "DataReturn:<br>"; print_r($DataReturn);
require './ExportAllToExcel.php';
}
This then sends the correct data to the ExportAllToExcel.php file and exports the data the users wants.
I've a problem. I'm working with javascript and PHP. This PHP code runs (as you can see from the numerous echo :D ) until the variable $curlResponse. Starting from this variable, and all the others variable to follow ($xmlObj, $translatedStr, $translatedText) are empty! Anyone can help me?
<?php
try {
$clientID = "XXX";
//Client Secret key of the application.
$clientSecret = "XXX";
//OAuth Url.
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
//Application Scope Url
$scopeUrl = "http://api.microsofttranslator.com";
//Application grant type
$grantType = "client_credentials";
// Create the AccessTokenAuthentication object.
$authObj = new AccessTokenAuthentication();
// Get the Access token.
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
// Create the authorization Header string.
$authHeader = "Authorization: Bearer ". $accessToken;
echo "<script type='text/javascript'>alert('$authHeader');</script>";
// Set the parameters.
// Sets source language. $fromLanguage = variable, langs[source][0] = name of textarea.
$fromLanguage = $_COOKIE['cookie_source'];
// Sets destination language. $toLanguage = variable, dest_lang = name of textarea.
$toLanguage = $_COOKIE['cookie_dest'];
// Sets text to translate. $inputStr = variable, source_text = content of thextarea.
$inputStr = $_COOKIE['cookie_final'];
echo "<script type='text/javascript'>alert('$inputStr');</script>";
$contentType = 'text/plain';
$category = 'general';
// Variable that composes the string of parameters for the transaltion
$paramst = "text=".urlencode($inputStr)."&to=".$toLanguage."&from=".$fromLanguage;
echo "<script type='text/javascript'>alert('$paramst');</script>";
// URL to translate the text
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$paramst";
echo "<script type='text/javascript'>alert('$translateUrl');</script>";
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
//Get the curlResponse.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
echo "<script type='text/javascript'>alert('$curlResponse');</script>";
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val) {
$translatedStr = $val;
}
echo "<script type='text/javascript'>alert('$translatedStr');</script>";
$translatedText = urlencode($translatedStr);
echo "<script type='text/javascript'>alert('$translatedText');</script>";
if (isset($inputStr)== true){
if ($translatedStr==''){
} else {
echo "<script type='text/javascript'>alert('e piena');</script>";
}
}
} catch (Exception $e) {
echo "Exception: ".$e->getMessage().PHP_EOL;
}
?>
Please specify from where you got the class files and why don't you use this source code available Here which I believe is working fine
<?php
/**
* This file will retuen JSON response
*/
require_once('config.inc.php');
require_once('class/ServicesJSON.class.php');
require_once('class/MicrosoftTranslator.class.php');
$translator = new MicrosoftTranslator(ACCOUNT_KEY);
$text_to_translate = $_REQUEST['text'];
$to = $_REQUEST['to'];
$from = $_REQUEST['from'];
$translator->translate($from, $to, $text_to_translate);
echo $translator->response->jsonResponse;
?>