JSON Tutorial

From MapbenderWiki

Jump to: navigation, search
under construction!

Contents

References

Task

Gather data from a database.

Template

client side

mb_ajax_json("<server side script filename>", {command:'command name'}, function(json, status){
    if (status == "success") {
        .
        .
        <do something with the json object (it already is an object, not a string)>
        .
        .
    }
    else {
        var e = new Mb_exception("AJAX query failed: " + status);
    }
});


server side

<?php
 
require(dirname(__FILE__)."/../../conf/mapbender.conf");
require_once(dirname(__FILE__)."/../extensions/JSON.php");
require_once(dirname(__FILE__)."/../classes/class_mb_exception.php");

$con = db_connect(DBSERVER,OWNER,PW);
db_select_db(DB,$con);

$command = $_GET["command"];

$obj = array(); 

if ($command == "<command>") {
	$sql = "<SQL statement>";
	$v = array(<values>);
	$t = array(<types>);
	$res = db_prep_query($sql, $v, $t);
	while($row = db_fetch_array($res)){
		<gather data from row>
		<add data to $obj>
	}
}
else if ($command == "<another command>") {
	.
	.
	.
}
else {
	// unknown command
	$e = new mb_exception("unknown command: " . $command);
} 

$json = new Services_JSON();
$output = $json->encode($obj);
echo $output;
?>
Personal tools