"Otto Wyss" <ot****@bluewin .chwrote in message
news:46******** **@news.bluewin .ch...
I've now been looking for a week for a simple but useful sample on how to
get a list of entries (persons) via an XMLHttpRequest using Json/PHP on
the server. So far I've found about a thousend different tutorials and
code samples but not a single one, where the server returns an array of
entries. Very few samples use Json at all and almost none show the server
code. So does anybody know a sample which
- uses just a small javascript library (preferable jQuery)
- uses Json/PHP and returns a list (array) of entries
- contains the full code, server and client side
- hopefully has a working demo on the web
Or does somebody have such a sample to share or put up on the web?
O. Wyss
I have the following sample running only on my development computer... it's
a very basic sample, no error handling or other gadgets...
Get "AjaxRequest.js " from:
http://www.ajaxtoolbox.com/request/source.php
(okay, this is the only gadget but a very basic and small(!!) library,
also.. read what Matt Kruse is writing!)
put the following 3 files in the same directory and run index.php
json.txt
{"employees" :[
{"name": "John", "id": 10},
{"name": "Jane", "id": 12},
{"name": "Tom", "id": 13},
{"name": "Jones", "id": 15}
]
}
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Sample 1</title>
<script type="text/javascript" src="AjaxReques t.js"></script>
<script type="text/javascript">
//<![CDATA[
var jsonobject;
window.onload = function(){
AjaxRequest.pos t(
{'url':'get.php ', 'parameters':{' list':'employee s'}
,'onSuccess':fu nction(req){
jsonobject = eval('('+req.re sponseText+')') ;
/* get the select element and fill the list from the json string */
var sel = document.getEle mentById("list1 ");
for (var i=0; i < jsonobject.empl oyees.length;i+ +){
addOptions(sel, jsonobject.empl oyees[i].id,
jsonobject.empl oyees[i].name);
}
}, 'onError':funct ion(req){ alert("Error!\n StatusText="+re q.statusText);}
});
}
function addOptions(obje ct, oValue, oText) {
/* very simple (old skool) method of adding list options */
var defaultSelected = true; var selected = true;
var optionName = new Option(oText, oValue, defaultSelected , selected)
var length = object.length;
object.options[length] = optionName;
}
//]]>
</script>
</head>
<body>
<select name="list1" id="list1" size="4">
</select>
</body>
</html>
get.php
<?php
$what = $_GET["list"];
if ($what = "employees" ){
$file = "json.txt";
header("Content-type: application/json; charset=utf-8");
header("Content-Transfer-Encoding: 8bit");
header("Content-Length: " . filesize($file) );
print(file_get_ contents($file) );
}else{
// another list?
}
?>