JSON

From XennisWiki
Jump to: navigation, search

JSON, or JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML. (Wikipedia)

Communication between JavaScript and PHP

JavaScript

Further information: jQuery.getJSON(), jQuery.post()

GAME.scorelist = (function (window, jQuery) {

    var location = "php/scores.php";

    return {
        getScoreList: function(callback) {
            $.getJSON(location, function (data) {
                callback(data);
            });
        },
        saveScore: function(name, score, callback) {
            $.post(location, {"name":name,"score":score}, function(data) {
                callback(data);
            }, "json");
        }
    }

})(window, jQuery, undefined);

PHP

Further infromation: json_decode, json_encode (see also PHP - SQL)

scores.php

<?php

// JSON standard mime header
header('Content-type: application/json');

if ($_SERVER['REQUEST_METHOD'] === "GET") {
	echo getHighscore();
} 
else if ($_SERVER['REQUEST_METHOD'] === "POST") {
	echo insertScore($_POST["name"], intval($_POST["score"]));
}

/**
 * Get highscore.
 *
 * @return JSON object with top ten highscore
 */
function getHighscore() {

	$highscores = array();
	$i = 0;

	$sql = "SELECT *
        	FROM   neversquare_scores
        	ORDER BY  score
        	LIMIT 10";
	$result = mysql_query($sql);
	while ($row = mysql_fetch_object($result)) {
		$highscores[$i]['name'] = $row->name;
		$highscores[$i]['score'] = $row->score;	
		$i++;	
	}
	mysql_free_result($result);

	return json_encode($highscores);
}

/**
 * Insert new score
 *
 * @param string name Player name
 * @param integer score Player score
 * @return JSON object true / false
 */
function insertScore($name, $score) {
	$returnValue = new stdClass();
	$returnValue->result = false;

	if (!empty($name) && (strlen($name) <= 20) && !empty($score)) {
		$sql = "INSERT INTO neversquare_scores
					VALUES ('$name', $score)";
		$returnValue->result = mysql_query($sql);
		//return $result;	
	}
	return json_encode($returnValue);
}

?>

See also

External links