473,388 Members | 1,256 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Ajax sample code with Json/PHP

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
Apr 9 '07 #1
5 16102
"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="AjaxRequest.js"></script>
<script type="text/javascript">
//<![CDATA[
var jsonobject;
window.onload = function(){
AjaxRequest.post(
{'url':'get.php', 'parameters':{'list':'employees'}
,'onSuccess':function(req){
jsonobject = eval('('+req.responseText+')');

/* get the select element and fill the list from the json string */
var sel = document.getElementById("list1");
for (var i=0; i < jsonobject.employees.length;i++){
addOptions(sel, jsonobject.employees[i].id,
jsonobject.employees[i].name);
}
}, 'onError':function(req){ alert("Error!\nStatusText="+req.statusText);}
});
}
function addOptions(object, 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?
}
?>
Apr 9 '07 #2
wyo
On Apr 9, 8:24 pm, "Marc" <sorry...@dirtymail.comwrote:
>
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!)
I must say I've already looked into Ajaxtoolbox but I've some
reservation to base a new development onto a source which hasn't
changed since June 22, 2005. Also the serializeForm doesn't use JSON
which IMO is a must. Anyway thanks a lot for the sample.
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?
}
?>
Why do you use headers in get.php? Are they necessary?

O. Wyss

Apr 10 '07 #3
<snip>
>
>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?
}
?>

Why do you use headers in get.php? Are they necessary?

O. Wyss
I use the headers because the RFC says so:
http://www.ietf.org/rfc/rfc4627.txt?number=4627

header("Content-type: application/json; charset=utf-8");
3. Encoding
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

6. IANA Considerations
The MIME media type for JSON text is application/json.
header("Content-Transfer-Encoding: 8bit");
6. IANA Considerations
Encoding considerations: 8bit if UTF-8
header("Content-Length: " . filesize($file));
because you simply should tell the client what size you are sending...

Most browsers don't care if you send the headers or not but in the future
other clients (read software) might want to use your json also...
Apr 10 '07 #4
<snip>
>>
>>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?
}
?>

Why do you use headers in get.php? Are they necessary?

O. Wyss

I use the headers because the RFC says so:
http://www.ietf.org/rfc/rfc4627.txt?number=4627

>header("Content-type: application/json; charset=utf-8");

3. Encoding
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

6. IANA Considerations
The MIME media type for JSON text is application/json.
>header("Content-Transfer-Encoding: 8bit");

6. IANA Considerations
Encoding considerations: 8bit if UTF-8

And oh... the code sample just sends the json string as whatever your
filesystem is using as encoding...
to send real utf-8 you could use the 'utf8_encode' function in php...
Apr 10 '07 #5
Marc wrote:
>>>?>
Why do you use headers in get.php? Are they necessary?

And oh... the code sample just sends the json string as whatever your
filesystem is using as encoding...
to send real utf-8 you could use the 'utf8_encode' function in php...
Thanks a lot, I just was curious since no other samples uses headers or
utf8_encode. I'll keep that in mind.

O. Wyss
Apr 10 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
by: Larry | last post by:
Hi there: I have seen numerous postings about eval() and its evils on this forum. However, one of our developers is using it in the following way, which seems like a great use of it. Page...
8
by: DartmanX | last post by:
Hi, Looking for recommendations for a decent API for AJAX work. I need it to be somewhat documented so I can figure out how to actually use it. My most critical need right now is clean code...
4
by: VK | last post by:
Google Trends is an all new service (started May 10) and I have not responsability for proper query or data accuracy. Overall seems pretty close to what could be observed by the post history in...
1
by: dan.goyette | last post by:
I'm fairly new to using AJAX. I'm currently developing a data grid application in coldfusion, using AJAX for paging/filter/sorting updates to the grid. So far I've just been returning raw html, and...
4
by: UKuser | last post by:
Hi, I'm working on the following code, which works fine in Firefox, but not in IE. The problem is its not posting the variable to my page and I'm thinking its something wrong with the...
6
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick...
11
by: kj | last post by:
I would like to convert a form that currently uses the traditional CGI sequence (i.e. the action associated with the form sends a POST request to a server-side CGI script) to one that uses AJAX to...
0
by: crocodilu2008 | last post by:
JSON vs. XML JSON and XML are basically used for the same purpose—to represent and interchange data. I'll try to show you why you might want to use JSON rather than XML in an AJAX context by showing...
3
by: George | last post by:
I am doing an AJAX call using JQuery on my page to which returns JSON objects and everything works fine. Now I decided to use ashx handler instead of and simply write JSON out. Then my problems...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.