Skip to content

Instantly share code, notes, and snippets.

@maxmonax
Last active March 12, 2017 14:57
Show Gist options
  • Save maxmonax/bcd88ca1f4518ab700d660c5adcafeaf to your computer and use it in GitHub Desktop.
Save maxmonax/bcd88ca1f4518ab700d660c5adcafeaf to your computer and use it in GitHub Desktop.
<?php
// Make sure that it is a POST request.
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {
throw new Exception('Request method must be POST!');
}
// Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if (stripos($contentType, 'application/json') === false) {
throw new Exception('Content type must be: application/json; BUT contentType = '.$contentType);
}
// Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
// Attempt to decode the incoming RAW post data from JSON.
// { nick: "nick", email: "mail", scores: 123 }
$decoded = json_decode($content, true);
// If json_decode failed, the JSON is invalid.
if (!is_array($decoded)) {
throw new Exception('Received content contained invalid JSON!');
}
// test
//print_r($decoded);
// Process the JSON.
$command = $decoded["command"];
$cnt = $decoded["cnt"]; // records count
if (strcasecmp($command, 'top') != 0) {
throw new Exception('Incorrect command: '.$command);
}
// DB CONNECTION
$username = "db_uname";
$password = "db_pass";
$hostname = "localhost";
$dbname = "myDB";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//echo "Connected to MySQL<br>";
$selected = mysql_select_db("monax_gamesdata", $dbhandle) or die("Could not select examples");
// execute the SQL query and return records
$result = mysql_query("SELECT email, nick, scores FROM branddush_scores ORDER BY scores DESC");
// fetch tha data from the database
//echo "result: ".$result;
$res = array();
while ($row = mysql_fetch_array($result) and $cnt > 0) {
//echo "email: ".$row{'id'}." Name:".$row{'model'}." ".$row{'year'}."<br>";
$arr = array(
'email' => $row["email"],
'nick' => $row["nick"],
'scores' => $row["scores"]
);
$res[] = $arr;
$cnt--;
}
//echo "done";
echo json_encode($res);
?>
refreshData() {
this.table = [];
var json = JSON.stringify({
command: 'top',
cnt: 10
});
try {
var xhr = new XMLHttpRequest();
var addr: string = this.game.cache.getJSON('config').server_getscores_addr;
xhr.open('POST', addr, false);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//console.log('xhr.responseText: ' + xhr.responseText);
};
};
// Отсылаем объект в формате JSON и с Content-Type application/json
// Сервер должен уметь такой Content-Type принимать и раскодировать
xhr.send(json);
//LogMng.log('xhr.responseText: ' + xhr.responseText);
}
catch (e) {
LogMng.log('LBMng XMLHttpRequest get: ' + e, LogMng.ERROR);
}
try {
var obj: Array<any> = JSON.parse(xhr.responseText);
//var obj: Array<any> = eval("(" + xhr.responseText + ")");
//LogMng.log('obj[0] = ' + obj[0]);
for (var i = 0; i < obj.length; i++) {
var t: TableItem = new TableItem(obj[i]['email'], obj[i]['nick'], obj[i]['scores']);
this.table.push(t);
}
}
catch (e) {
LogMng.log('LBMng json parse: ' + e, LogMng.ERROR);
}
}
<?php
// Make sure that it is a POST request.
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {
throw new Exception('Request method must be POST!');
}
// Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
//if (strcasecmp($contentType, 'application/json') != 0) {
//throw new Exception('Content type must be: application/json, but it = '.$contentType);
//}
if (stripos($contentType, 'application/json') === false) {
throw new Exception('Content type must be: application/json; BUT contentType = '.$contentType);
}
// Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
// Attempt to decode the incoming RAW post data from JSON.
// { nick: "nick", email: "mail", scores: 123 }
$decoded = json_decode($content, true);
// If json_decode failed, the JSON is invalid.
if (!is_array($decoded)) {
throw new Exception('Received content contained invalid JSON!');
}
// test
//print_r($decoded);
// Process the JSON.
//echo $decoded["email"];
//echo $decoded["nick"];
//echo $decoded["scores"];
// DB CONNECTION
$username = "db_uname";
$password = "db_pass";
$hostname = "localhost";
$dbname = "myDB";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//echo "Connected to MySQL<br>";
$selected = mysql_select_db("monax_gamesdata", $dbhandle) or die("Could not select examples");
$email = $decoded["email"];
$nick = $decoded["nick"];
$scores = $decoded["scores"];
$query = "INSERT INTO `monax_gamesdata`.`branddush_scores` (`email`, `nick`, `scores`) VALUES ('$email', '$nick', $scores);";
mysql_query($query);
echo "done";
?>
sendScores(aEmail: string, aNick: string, aScores: number) {
var json = JSON.stringify({
email: aEmail,
nick: aNick,
scores: aScores
});
try {
var xhr = new XMLHttpRequest();
var addr: string = this.game.cache.getJSON('config').server_sendscores_addr;
xhr.open('POST', addr, false);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log('xhr.responseText: ' + xhr.responseText);
};
};
// Отсылаем объект в формате JSON и с Content-Type application/json
// Сервер должен уметь такой Content-Type принимать и раскодировать
xhr.send(json);
}
catch (e) {
LogMng.log('LBMng XMLHttpRequest send: ' + e, LogMng.ERROR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment