473,756 Members | 2,378 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 16133
"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?
}
?>
Apr 9 '07 #2
wyo
On Apr 9, 8:24 pm, "Marc" <sorry...@dirty mail.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("Conten t-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("Conten t-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
3432
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 makes Ajax request to ASP.Net web service. Web service does some data lookup and builds a string representation of a Javascript array which is then returned to the client. In the ajax callback, call to eval on the returned string and voila, ...
8
2077
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 for a "triple" chained selector (state->county->city). Jason
4
4060
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 c.l.j. Just curious why exactly Japan got so exclusively hot on JSON ? <http://www.google.com/trends?q=AJAX+JavaScript&ctab=0&geo=all&date=all> <http://www.google.com/trends?q=JSON+JavaScript&ctab=0&geo=all&date=all>
1
2512
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 updating the innerHTML of a div on the page when the response comes back. But now I've decided it would be useful to split my response into (at least) two parts. The first will be the raw HTML to place in the div. The second part will be...
4
2545
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 getElementByID but the code is as per an example on a tutorial website (http://www.tizag.com/ ajaxTutorial/ajax-javascript.php). The Select element is as follows: <select style="width:240px;font-size:8pt" id='servicet'
6
5166
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 application working. However, when attempting to implement the solution, the AJAX calls weren't updating the screen like the examples were and seemed not to fire until after the long running process had completed. I found the only real...
11
8410
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 send a JSON-encoded request to a remote web service. The stumbling block I'm running into is that one of the inputs in the form is a file upload element, and I can't figure out how to include the data from the specified file in the JSON...
0
5381
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 you an example of how an data class (actually, a list of PHP documentation pages) might be represented, first in XML. and then in JSON. This side-by-side comparison should let you begin to understand how to represent data in JSON. The XML version:...
3
17693
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 begun. So here is JQuery call $.ajax({ type: 'POST', url: url,
0
9255
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10014
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.