Ajax Trong PHP
Ajax Trong PHP
W
ytare Lrdler^ip
Trung tm o to lp trnh vin quc t AiTi-Aptech
Trnh by: Nguyn Thanh Nam - AiTi-Aptech Faculty
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
f a. l o. l s
Ni dung hi tho
vtan oi Leadership
Gii thiu v PHP
C php trong PHP
AJAX
Music website using PHP & AJAX
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
facebook
Vietnam
Cy WORL P
Th%vut-mt ft 4t*ig
TRANG CHU CAU LAC BO SHOP P1CTURA KINE ALOHA
Mtkhu:
Ghi nhddiachi Email
Banquenmatkhau?
CHUYEN NHA
TII365
Facebook hel ps you connect and share wi t h
t he people in your l if e.
Sign Up
It's free and anyone can join
4ssj quatigtS!
111ul l i eh .i l l l i l t
Si l i l i VM1 l > i l u i r I,CM-
iS&Z
J fcr...... A '.
Pi--.....
A "%
Tbcfl Stax b"
vng 1t W/5 (tn Z4h ngi
vng lh sng ngy 14/4 Mn 2h ngi
a tea page for a celebrity, band or business, click hi
Get Y ahoo! Toolbar with Anti-Spy
' X H o O f
Web Images Video Local Shopping more
See the latest environmentally friendly
Search:
L
Web Search
I mai n page | discussion | | view source | | history |
Welcome to Wikipedia,
the free encyclopedia that anyone can edit.
2,358,644 articles in English
Overview Editing Questions Help
digg Joi n Di gg About Logi n
Apr 28,2009 I Page Optif
Sports I Video
Technology v World &Business v Science r Gaming v Lifestyle v Entertainment v Sports v Offbeat *
ne f lu: 5 t hi ngs to know
world may be on the brink of the first
inza pandemic in more than 40
3. Are we ready for i t?
it pandemics Flu basics
S tatistics
r T v' s tai
Hi id085 S g i
Mail ( ^) M essenger Puz;
- Weather
83 F
Pop u l ar Upcoming SETA News Videos Images Customize
Yah o o ! Sp o r t s s h o p
Your Source for Final Four gear
1,000 factory
News, Images, Videos I opIn24Hr 7Days 30Days 365Days
ftQ i Digg Dialogg with Sir Richard Branson!
I I L Submit your questions for our next Digg Dialogg with Virgin Group founder Sir Richard Branson, presented by Freecreditreport ci
How Swine Flu Spreads from Pigs to Humans
image growatrain.typepas.com(Pets&Animals: maflepopular 14mlnago
5SComments Share Bury 4*I msaleemsubmitted
Running Windows 7 RC on a netbook
GA ME OF Tl
UFT
IN STORE
THli
MU) W o k d P r e s s .
J8___S
r VWdPr&ss.canB''S: Q
COM
Home SignUp Features Blog Our Story Advanced
diggs wo9s.computerwona.com How does Microsoft's latest Windows 7 leak. Build 7100 run on a netbook, the Dell Mini 9 in specific? Here's y
what I found. More,.. fMicrowHR
digg 22Comments Share Bury sjvnmadepopular 14minago 3558 U I The Me
214
diggs
digg
Prometheus Creating Saturn Ring Streamers
IMAGE apod.nasa.gov(Space) madepopular24mmago
10Comments Share Bury louiebaursubmitted
Express yourself. Start a blog.
1
Sign Up Nowl
Seeour freefeatures *
1
173,004 BLOGGERS. 184,512 MEWPOSTS. 46,787,330 WORDS TODAY. PreferredLanguage: English
Wordpress.comisalsoavailableinTl
"9l4'-
Viral Flu: EarthsOldest Trojan Horse-invaders
EASYREADINGCULTUREOFLIFENEWS: VIRALFLU: EARTH'S
OLDESTTROJ ANHORSE-INVADERSCultureof UfaNews2
Virusesareoneof theElderEarthLifeForms. Theyuseusas
theirTrojanHorsestoinvadenewterritory. I wasone[...]
Cultureof LifeWws
100
} , vt'ars i Leadership
PHP l g?
M hnh hot ng
Lch s pht trin
L do s dng
Cc con s
PHP l g ?
PHP c pht trin t ngn ng kch bn (script) vi mc ch
xy dng trang Web c nhn (Personal Home Page). Sau
c pht trin thnh mt ngn ng hon chnh v c a
chung trn ton th gii trong vic pht trin cc ng dng Web
based
PHP (PHP: Hypertext Perprocessor) l ngn ng kch bn lp
trnh pha my ch (server-side) ph bin nht th gii
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
APTECH
TM
year* Leadership
PHP thng hot ng theo th t sau:
1. Ngi dng gi yu cu ln my ch
2. My ch x l yu cu (Thng dch m PHP v chy chng
trnh, m PHP c th truy xut CSDL, to hnh nh, c ghi
file, tng tc vi my ch khc...)
3. My ch gi d liu v cho ngi dng (thng l di dng
HTML)
ApLeth Lckbutcj
irk M h n h \ \ c \ \ i nn
'Da r tmw.CTaropkiDiTT,
pteeenrt me/ catoMml
Your desktop PC
Internet
4*'s t tip : //v w flxampli jMfli /oatj k>g/yjk.php
Wb Server
wwv/.exampl&cm
Web Server
Aplech
^ L ch s pht trin
yean oi Leadership
PHP c pht trin nm 1994, bao gm cc macro cho trang
Web c nhn (Personal Home Page) bi Rasmus Lerdorf.
PHP 2 (1995) nng cp thm mt vi chc nng mi hon thin
hn so vi phin bn u tin. (H tr Database, file upload, array,
conditionals, iteration, regular expressions...)
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
APTECH
TM
Apteih
^ L ch s pht trin
yean oi Leadership
PHP 3 (1998) c pht trin vi b dch mi vi tc nhanh
hn v khc phc nhng nhc im trong phin bn trc y
bi Zeev Suraski v Andi Gutmans. Phin bn ny cn h tr
thm ODBC v cc hm lm vic vi giao thc email (SMTP,
IMAP ).
PHP 4 (2000) Nng cp b dch hon thin hn vi vic h tr
nhiu tnh nng bo mt trong PHP. B dch c i tn thnh
Zend Engine.
PHP 5 (2004) c nng cp ln Zend Engine II vi kh nng lp
t^^rng i tng. APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech .eu.vn
Aplrdl t,ctebrJ t
( * L ch s pht trin
vtan oi Lcadcrship
Tnh n thng 7 nm 2007 PHP c s dng trn 20,917,850
domain vi 1,224,183 IP address.
PHP Usage for J ul 2007
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. eu.vn
L do s dng
1. D dng s dng
Code php c nhng ngay trong code HTML. PHP code s c
nm trong mt cp th c bit iu ny gip trnh x l d dng
phn bit code php so vi code HTML.
<html>
<head>
<title>Example</title>
</head>
<body>
echo "Hi, I'm a PHP script!";
<?
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
APTECH
TM
L do s dng
2. Tc thc thi
Zdnet Statistics
s PHP pumped out about 47 pages/second
s Microsoft ASP pumped out about 43 pages/second
s Allaire ColdFusion pumped out about 29 pages/second
s Sun J ava J SP pumped out about 13 pages/second
* T7---------- T T T T J u l y 2 0 0 1
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
APTECH
TM
ApLech Lkbrjtes
L do s dng
3 Tmh kh chun
PHP c thit k chy trn nhiu nn tng khc nhau, c th
lm vic vi nhiu phn mm my ch, c s d liu (v d: bn
c th pht trin d n trn UNIX, sau chuyn sang NT m
khng gp phi bt c vn g)
Web Servers: Apache, Microsoft ns, Caudium, Netscape
Enterprise Server
Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux),
Mac OSx7 Windows NT/98/2000/XP/2003
Supported Databases: IBM DB2, Informix, InterBase,
rontBase, Direct MS-SQL, MySQL, ODBC, Oracle ...
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech edu.vn
L do s dng
4. Gi thnh cnh tranh
PHP khng ch l phn mm m ngun m m cn thc s min
ph (k c khi bn s dng cho mc ch thng mi). Do l phn
mm m ngun m, cc li (bug) ca PHP c cng khai v
nhanh chng c sa cha bi nhiu chuyn gia do n cng
c min ph.
PHP
Software Free
Platform Free (Linux)
PHP Coder, Edit
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
APTECH
TM
vean oLtadcrship
5. PHP c mt cng ng pht trin mnh
6. Thi gian pht trin d n nhanh
Do PHP c mt cng ng ln mnh nn rt nhiu cc ti liu
hng dn, nhng th vin code, thm ch nhng ng dng hon
thin u c cung cp min ph. Nn khi pht trin ng dng
s gim c rt nhiu thi gian.
*g PH P
a. Hn 40 % ng dng Web c vit bng PHP
b. Hn 20 triu website s dng PHP
c. Hn 45% cc my ch Apache ci t PHP
2. T kha PHP tr v kt qu 9.380.000.000 khi tm kim trn Googl e so
vi 2.550.000.000 ca ASP , 634.000.000 ca JSP v 75.800.000 ca
ASP.NET.
3. Hu ht cc website ni ting u ang s dng code PHP nh
Facebook, Wikipedia (MediaWiki), Yahoo!, My Yearbook, Digg,
WordPress v Tagged.
yean oi Leadership
Google trend
php i.3o jsp o13 asp ^3.28 asp.net 32v
Apr 20Q JUI208 Oci 200
I I p i I r- I I i-1 I I
News reference volume
C php PHP
ApLech Lkbtjtci
f / |
r w
yean. i Leadership
Tag style Start Tag End Tag
Standard <?php ?>
Short <? ?>
ASP <% %>
Script tags cscript
language=ph
p>
</script>
* Nn dng kiu standard
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
Cu phap trong PHP
.tan. udLeadership
Chu thich trong PHP
<html>
<head>
<title>This is a PHP program</title>
</head>
<body>
<b>
<?php
// Print Hello world
echo("Hello world");
/* Comment like that is ok*/
# It's acceptable
/ * *
* API Document
* /
? >
</b>
</body>
</html>
years oLrjdrrvhip
Bin trong PHP
s Bin khng bt u bng s, khng c trng tn hm, phn
bit kiu ch
S Khng cn khai bo trc
s ly gi tr bin dng k hiu $ trc tn bin, bin c th b
p kiu
s nh ngha hng dng define
vd: define(pi,3.14);
S Bin c tm vc trong hm, trong script
1 Q
i tar i oJ Lrji dkrrdisip
ApLedi Lclcbrales
Vi du:
<?php
$var = "Aiti";
$Var = "Aptech";
echo "$var, $Var"; // outputs "Aiti, //Aptech"
$4site = 'not yet1; //invalid
$_4site = 'not yet1; // valid;
$tayte = 'mansikka1; // valid; 'a' is //(Extended)
ASCII 228.
? >
Cu phap PHP
vears oLtadcrship
Php ton
s PHP cung cp cc php ton s hc(+, - ...)
s Cc php ton kt hp (+=, -=)
s Php tham chiu &
S Php so snh (= =, !=, >, <, >=, <=. . . )
S Php ton logic (II, &&, !)
S Php ton Error @
ApLech (.ctebnltes
t
Cu phap PHP
vtan. oJ Leadership
Kieu dir lieu
S Scalar : Boolean, Integer, Float, String
S Composite : Array, Object
S Special Types : Resource, NULL
CuphapPHP
vtarh udLrjidkrr ship
Khai bao mang
ApLeth LdcbuL^
<?php
$ar = array(3,4,5,6,3,2);
echo var_dump($ar), "<br>";
$ar = array(5=>10, 20, 30, "q"=>40);
echo var_dump($ar), "<br>";
$ar = array(5=>10, 6=>20, 7=>30, "q"=>40);
echo var_dump($ar), "<br>";
$ar = array("a"=>10, 20, 30, 40);
echo var_dump($ar), "<br>";
$ar = array("a"=>array(1,2,3,4,5), 20, 30, 40);
echo var_dump($ar);
?>
11j,'iULI1UUIM.fl
&
Cu phap PHP
Mtarsid Leadership
<?php
if ($a > $b)
echo "a is
$b = $a;
}
if ($a > $b)
echo "a is
}
else
{
echo "a is
}
if ($a > $b)
echo "a is
}
elseif ($a
echo "a is
}
else
{
echo "a is
}
? >
Cau lenh IF
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Cu phap PHP
C4u lenh SWITCH
<?php
if ($i == 0) {
print 11 i equals 0";
} elseif ($i == 1) {
print "i equals 1";
} elseif ($i ==2) {
print 11 i equals 2";
}
switch ($i) {
case 0:
print 11 i equals 0";
break;
case 1:
print 11 i equals 1";
break;
case 2:
print "i equals 2";
break;
}
? >
ApLci cel ebrates
Mtars i d L r ji Jer d i si p
C php PHP
<?php
$ i = 1 ;
while ($i <= 10)
print $i++;
}
$ i 1
while ($i <= 10):
print $i;
$i++;
endwhile;
Cu lnh WHILE .. DO
$i = 0;
do {
print $i;
} while ($i > 0);
? >
7<"J CphpPHP
y tar h od L ta l cr s h i p
Cu lnh FOR
<?php echo "--------------------\n" ;
echo "------------------- \n" ; $i = 1;
for ($i =1; $i <= 10; $i++) { for (;;) {
print "$i\n"; if ($i > 10)break;
} print "$i\n";
$i++;
echo "------------------- \n" ; }
for ($i =1; ; $i++) {
if ($i > 10) break; echo "--------------------\n" ;
print "$i\n"; for ($i =1; $i <= 10;
} print "$i\n", $i++);
echo "------------------ \n" ;
for ($i = 1; $i<=20; $i++):
print M$i\nM;
endfor
?>
ApLedl LdbuL.
/<2 CuphapPHP
vtan. udLrjidkrr Jsip
Khai bao ham
<?php
function square ($num) {
return $num * $num;
}
echo square (4); // outputs '16'.
function small_numbers() {
return array (0, 1, 2);
}
list ($zero, $one, $two) = small numbers();
/< ^ K6t n6i CSDL
vtan. odLeadership
ApLeth i d '.'b u k :
Ket noi CSDL
if(!($conn =@mysql_connect("localhost","root","root")))
{
die("Could Not Connect");
}
mysql_select_db("music", $conn);
//PERFORM QUERY
$sql = "SELECT * FROM tblX";
$result = mysql query($sql,$conn);
Aplrdl ccfcbfiiles
PHP
vtfan oi Leadership
Lin kt chnh thc
Apache http://apache.org/
PHP http://php.ne
MySQL http://mysql.com/
Cc b ci t tch hp
APPSERVER http ://www. appservnetwork.com/
EAS YPHP http ://www. eas vphp. or g/index .php
XAMPP http://apachefiiends.org/
WAMP http://www.wampserver.com/en/
Manual install http://www.expertsrt.com/tutorials/Matinstall-apache.html
APTECH
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e u . v n
APTECH
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
1. Gii thiu Ajax
2. Kin trc Ajax
3. Ba bc lp trnh vi Ajax
4. Demo v d Ajax & PHP
years Leadership
Aplrdl ccfcbfiilES
&
vtan oi Leadership
AJ AX
1. Gii thiu Ajax
ng dng Desktop
s Ton b m CT chy trn Desktop
s Tc thc thi/Tnh tng tc cao
s Rich Client?
ng dng Web
'S Click-wait-refresh-Click-wait-refesh
ng dng RPC/RMI
'S Phc tp, nng n trong x l
'S nh hng bi Network Latency
Go
1V
vean. irf Leadership
A p l r i h L ck b u tcs
Fx
vodRIA
'W
Silverlight
M
Y .. O p e n L a s z l o
\ \
Desktop
Web
Applications
Applications
-
RIA
Communication
Technologies
APTECH
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
Aplrdl ccfcbfiiles
vtan. oi Leadership
AJ AX
1. Gii thiu Ajax
ng dng Rich Internet Application
'S Adobe Flash/Flex Apps
'S Microsoft Silverlight Apps
'S Ajax Applications
u im
'S Truy cp bt ng b
'S a dng trong tng tc
'S C th to cc ng dng phc tp
'S Gim ti cho server ...
is
[email protected] I New features I Docs Home I Helc
/ <2 ^ aj ax
' ^ 1. Gii thiu Ajax
Ajax l g ?
o Tn ca th mt nc ?
o Tn ca mt i bng ?
o Ajax l tn ca mt cng ngh ?
A p L eth L c k b u tc s
9 vtan. oi Leadership
AJAX = Asynchronous JavaScript And XML : thut ng c
a ra bi Jesse James Garret nm 2005 trong bi vit c tn
AJAX : A New Approach to Web Application [1]
APTECH
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
AJ AX
Aplrdl (.ctebnltes
&
i P X
vtan oi Leadership
AJAX phi c vit chnh xc l Ajax
AJAX : acronym (t vit tt cc ch ci u)
Ajax : tn ca mt t hp cng ngh, trong nhn mnh
A = Asynchronous - Tnh bt i xng
Ajax
Ajax khng phi l mt ngn ng hay mt cng ngh
Ajax l t hp cc cng ngh gip ng dng Web gn vi
Desktop bng cch loi b s Refresh ca trang web. T hp
XHTML + css : trnh din ni dung
DOM : hin th ng v tng tc vi cc elements
XML + XSLT : nh dng d liu cho trao i, thao tc
XMLHttpRequest : gi v nhn Request
JAVASCRIPT: kt dnh cc thnh phn
gm :
APTECH
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
Ajax
u im ca Aj ax
Data-driven : gim ti cho server do ch cn chuyn data
Click v Wait nhng khng refresh -> ging Desktop
Tc response nhanh hn
Ngi dng tip tc lm cc thao tc khc khi i
L cng ngh ca Browser, c lp vi Web Server
JUST-IN-TIME
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
APTECH
TM
Percent age of Mal chi ng Job Posti ngs
O
O'!
d
a
m
p
e
r
)
J
y
c
;
w
A p l r i h L c k b u tc s
pyears O Leadership
Ajax
Kin trc Ajax
r
V
Wob server
j
APTECH
COMPUTER EDUCATI ON
WWW. aitr-aptech.edu.vn
ApLedi celebtales
/<
'
vrs:df LrsIiip
Classic web app
^ \
Login_____________
Web
page
Web
page
Web
page
Exit
page
Logout
User's
data
model
JFsusines^^
nL logi-cM
H > r
User
session
Shared
data
model
Ai ax
Kin trc Ajax
Ajax app
Ajax
Ni dung gi qua ng dng web thng thng
]] Data
I Branding
I Content
Logout
APTECH
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e u . v n
ApLech Lckbutcs
/ ( ^
vtan. oi Leadership
Ni
(B)H
_ i
J ZL
Login
i I I I I I I I I I r
Time
I Data
I Presentation
Logic
Logout
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
dung giri qua ng dung web bang Ajax
ApLech ccfcbfitles
t
vtan. oJ Leadership
Ajax
Traffic tich ly
(C)
Classic
^ Aj ax
APTECH
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
Ajax
Khi no v u s dng Ajax trong ng dng web
Khi cn t ng Update nhng loi b Refresh (v d: Bng t s,
chng khon, u gi, d bo thi tit...)
Ti thiu tn s t ng Update gim ti cho server, cung cp link
refresh d nhn bit cho ngi dng.
thc vic s dng Back/Forward button, hoc chia s URL ca user
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
APTECH
TM
Ajax
Khi no v u s dng Ajax trong ng dng web (tip...)
Loi b s ph thuc gia thng tin v cc trang web (v d Google
Maps, Ajax pagination), s dng XML v raw Data
Ket hp Ajax vi Traditional HTML h tr ti u ha my tm kim
n gin ha cc thao tc thm, sa, xa, thng bo
Gip ngi s dng nhn bit cc action ang c thc hin (S
dng Ajax indicator image : Loading/Saving/Success .
on ton bng Ajax
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
APTECH
TM
Ajax
Ti sao Ajax v PHP?
Javascript v PHP c nhiu im chung.
PHP l nn tng m ngy cng m rng v ph bin
H tr bi cng ng ln (m ngun, ti nguyn,...)
Nh nhng (lightweight) v tc (speed) trong x l.
Hot ng c lp, d trin khai trn mi h thng (OS)
thao tc vi nh dng d liu.
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
APTECH
TM
Ba bc to mt ng dng
Ajax n gin
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. eu.vn
veano Leadership
Ba bc to mt ng dng Ajax n gin
SBc 1: Trigger s kin (JAVASCRIPT)
s Bc 2: Thao tc vi Ajax (CLIENT-SERVER)
v' Bc 3: Cp nhp giao din qua DOM (HTML+CSS+JS)
Bc 1: Trigger s kin (JAVASCRIPT EVENT)
years ai Leadership
S kin trong Javascript
onCl i ck onChange onEr r or
onBl ur onFocus onUnl oad
onSubmi t onMouseUp onResi ze
onMouseDown onMouseOver onSel ect
onMouseOut onMouseMove onMove
onKeyDown onKeyUp onLoad
onKeyPr ess onReset onAbor t
ApLcdi celebrates
/
Mtars id LLiJerdip
A j ax
Mo hinh dang ky su>kien
/ / xac di nh HTML el ement
var el ement = document . getElementByld( " el ement _i d" ) ;
/ / dang ky ham di eu khi en su ki en
el ement . onclick = execut eAj axSear ch;
/ / di nh nghi a ham di eu khi en su ki en
f unct i on execut eAj axSear ch( e)
{
/ / t ao connect i on
/ / gui r equest t oi ser ver
s Bc 2: Thao tc vi Ajax (CLIENT-SERVER)
2.1. Khi to i tng Request (XMLHttpRequest- XHR)
2.2. Vit hm Callback
2.3. Gi Request ti Server
2.4. Nhn v parse d liu tr v.
w
years i Lrjtkrvhip
Ajax
2.1. Khi to tng Request
Vi IE6: s dng Msxml2.XMLHTTP:
XMLHttp = new Acti veXObj ect(" M sxml2. XMLHTTP");
Vi IE5.6: s dng Microsoft.XMLHTTP
XMLHttp = new ActiveXObject( " Microsoft. XMLHTTP );
Vi trnh duyt khc: XMLHttpRequest (W3C)
XMLHttp=new XMLHttpRequestO;
Ajax
M khai tao tong qut
f unct i on Get Xml Ht t pObj ect {
t r y {
/ / Tao XHR t heo W3C
}
cat ch( e) {
t r y {
/ / Tao XHR cho I E6
}
cat ch (el ) {
/ / Tao XHR cho I E5. 6
r et ur n XHR
Cc phong thc c XMLHttpRequest
yearv iii Lrjtkrship
Methods
open( "met hod", "url ", Thi t l p r equest obj ect gi mt
asynchFl ag, ur s, pass) r equest l n ser ver
send( cont ent ) Gi request ln server, ni dung C
th null
abort() Dng r equest
getAHResponseHeaders () Tr l i t t c r esponse header cho
HTTP r equest dng key/ val ue
getResponseHeader("header ") Tr l i gi t r ( st ri ng) ca header
c t h
setRequestHeader( "header ", "
val ue")
Gn gi t r header c t h
veano Leadershi p
Cc thuc tnh ca XMLHttpRequest
Properties
onreadystatechange Ch nh hmcal l back
readyState Tr ng t hi Request : O- Khi to,
ang ti , 2- ti , 3- Tng tc,
Hon t t
1-
4-
responseText D l i u t ser ver dng t ext
responseXML D l i u t ser ver dng XML
status M t r ng t hi HTTP t ser ver cho
r equest c gi : 2OO- OK, 201-
Cr eat ed, 400- bad r equest , 403-
f or bi dden, 500- i nt er nal ser ver er r or
statusText Phi n bn t ext ca m t r ng t hi HTTP
Chi tit v cc trng thi
readyState=0: Cha khi to: sau khi to i tng
XMLHttpRequest nhng cha gi open().
readyState=l: Va khi to: sau khi gi open() nhng cha gi
send().
readyState=2: Va gi i: ngay sau khi gi send().
readyState=3: ang x l: sau khi kt ni n server nhng server
cha tr li.
readyState=4: Xong:sau khi server tnh ton xong, d liu gi v
APTECH
ytare O Lrjitkf ship
2.2. Vit hm callback
Callback function: l hm javascript c g kh thuc
tnh readystate thay i trn i tng XHR
S kh ca hm callback dng
f unct i on cbHandl eAj axResponse {
/ / t hao t c vi d l i u t r v t i t ng XHR
Ly i tng XHTTPRequest
var xhr Obj =Get Xml Ht t pObj ect () ;
Thit t onreadystatechange ti hm callback
xhr Obj . onr eadyst at echange = cbHandl eAj axResponse
M Request trn i tng XHR
xhr Obj . open("method","url",asynchflag);
- ur l : l i n kt cn kt ni t i
- asynchf l ag: t r ue (nu gi bt ng b)
Gi Request thng qua i tng XHR
=xhrObj . send ( cont ent ) ;
APTECH
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
y ears oLrjdrrvhip
Chn Method gi Request
Method = GET nu
Mc ich nhn d liu t server
REST (Representational State Transfer) webservices
Khi passing parameters
Cc URL khng thay i
Lng d liu gi l nh
Method = POST nu
Thay i (CUD) trong CSDL
Lng d liu gi ln server ln
Cc URL k c nh
2.4. Nhn v parse d liu tr v
f unct i on cbHandl eAj axResponse {
i f ( r esponse i s val i d) {
/ / get r esponseText or r esonseXML
/ / pr ocessi ng dat a
/ / get ar ea t hat need updat i ng
/ / st uf f val ue t o ar ea
}
}
Bc 3: Cp nhp DOM
Trnh duyt hin th giao din nh mt tp cc elements
l/ o M.
Mt trang web c dng cy vi quan h ch-con
Cy elements c gi l Document Object Model
Mi thay i vi DOM s phn nh ngay trn trnh duyt
yean dLeadership
Mot vi du v DOM
html r
V
head
r
t i t l e --Al chemy f or begi nner s
scri pt
body
h i
i mg
Chapt er 1: Equi pment
V ^ Th is is what an
em ^ al chemi st s' bot t l e
l ooks l i ke:
a !
APTECH
COMPUTER EDUCATI ON
Ajax
S dng DOM
Tng tc vi DOM nh Javascript
Tm DOM elements : document. getElementByld () ,
parentNode, chldNodes
Thm element mi : nnerHTML, createElement () ,
createTextNode(), insertBefore()
Lo b mt element: removeChidO
' 9
nh element: setAttributeQ, style
COMPUTER EDUCATI ON
WWW. a i t i - a p t e c h . e d u . v n
APTECH
TM
ApLcdi celebrates
/
yearsidLLaiJerdip
Ajax
Vi du sir dung DOM
<di v i d=" semi nar ">
<di v i d=" aj ax">Hel l o Aj ax</ di v>"
</ di v>
<scr i pt l anguage="j avascr i pt ">
var di vAj ax = document . get El ement Byl d("aj ax" ) ;
var di vSemi nar =
document . get El ement Byl d(" semi nar " );
var di vPHP = document . cr eat eEl ement (" di v" );
di vPHP. set At t r i but e(" i d" , " php" );
di vPHP. i nner HTML = "Hel l o PHP";
di vSemi nar . i nser t Bef or e( di vPHP, di vAj ax) ;
</ scr i pt >
Hello Ajax
Hello PHP
Hello Ajax
APTECH
COMPUTER EDUCATI ON
w w w . a i t i - a p t e c h . e d u . v n
Mt s lu
Tch style, m javascript ra kh n dung HTML d
truy xut v bo tr hn
Tao vn bn HTML theo chun XHTML
Vit m markup sch
yean oi Leadership
Demo Ajax Music Search
5. nh dang d liu JSON v XML
o
6. Xy dng Widget n gin cho Web vi Ajax
7. Ajax Toolkits
8. Vn v thch thc vi ng dng Ajax
9. Gii thu cc t nguyn, tham kho.
yearv iii Leadership
years oLrjdrrvhip
5. nh dng d liu XML
XML l g ?
extensible Markup Language
nh dng d liu ph bin nht cho p trnh
XHTML, Webservices, XML-based Database...
X (Ajax) ~XML v XMLHttpRequest XML
XML lin kt vi Ajax trong mi trng hp ? ->WRONG !
Thc t : Khng phi bt c ng dng Ajax no cng dng XML
y ears oLrjdrrvhip
5. nh dng d liu XML
XMLHttpRequest thc t ch gi mt HTTP request ti Server, bt k d
liu i cngn l Plain Text, Attribute/Value, XML, hay JSON.
Tuy nhin khng th i tn v c hng triu developer v ng dng s
dng ti i tng ny.
A k .
F
1 < ? x m ! ? >
r
APTECH
v ean Lrditlei shi p
5. nh dng d liu XML
<?xml version="l.0" encoding=" utf-8M?>
<bookList>
<book isbn="123">
<title> Ajax in depth</title>
<author>Nicholas Peter</author>
<publsher>Mannng</publsher>
</book> <book isbn="456">
<title>Pro PHP </title>
<author>Paul c. Zakas</author>
<publisher>FirstNew</publisher>
</book>
</bookList>
y ears oLrjdrrvhip
5. nh dng d liu XML
XML l inh dang chun cho cc dich vu Web
o
XML thc t chm hn khi truyn so vi Plain Text v JSON
Cu trc XML d hiu nhng khng n gin xy dng
Gp phi vn tng thch trnh duyt khi parse vn bn XML
Trong mi trng hp, xem xt s dng Plain Text, Cp Attribute /Value
hoc JSON, sau mi ti XML
veano Leadershi p
5. nh dng d liu JSON
JSON - Javascript Object Notion - JSON.org
nh dng d liu lightweight
Gia trn c php JavaScript (Array v Object literals)
JSON cho php chuyn cc i tng Javascript thnh cc chui c th
gi cng http request.
JSON c h tr bi hu ht cc ngn ng, vi PHP : JSON.php thnh
phn th vin h tr encode/decode nh dng chui sang PHP Object v
ngc li
Thn thin vi Developer, n nh, c chp nhn rng ri
APTECH
5. Dinh dang dir lieu JSON
o
var people =
{"programmers": [
{"firstName": "Brett", "lastName":"McLaughlin"},
{"firstName": "Jason", "lastName":"Hunter},
{"firstName": "Elliotte", "lastName":"Harold }],
"authors": [
{"firstName": "Isaac", "lastName": "Asimov", "genre": "Sciencefiction" },
{"firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{"firstName": "Frank", "lastName": "Peretti", "genre": "Christian fiction" }],
"musicians": [
{"firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{"firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }]
5. inh dang d liu JSON
o
Truy cp v thay i d liu
peopl e. pr ogr ammer s[ 0] . l ast Name;
peopl e. pr ogr ammer s[ 0] . l ast Name = "Boss";
Chuyn mng thnh string
j sonText = J SON. st r i ngi f y( peopl e) ;
Chuyn i tng thnh string
j sonText = J SON. st r i ngi f y( aper son) ;
year Leadership
Demo Ajax & XML
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
www.netvibes.com
years Leadership
6. Ajax, Widget, v Webservices
Web 2.0 - Web l nn tng gm nhiu dch y (Web-services)
M a p s , Search, Desktop,
Picasa, Sitemaps, Geo, OpenSocial
Adwords, Finance, Calendar,
Authentication, Ajax Search, Ajax
Language, Ajax Feed, Visualization,
03D, Book, Google Earth, Blogger
Data, Google Base
del.icio.us, Finance, flickr, Hot Jobs,
Maps, Merchant Solutions, Music, Design
Patterns, RSS Feeds, Search, Search
Marketing, Shopping, Travel, Traffic,
upcoming.org, Ul library, weather,
webjay,Widgets, JS Developer Center, PHP
Developer Center
H x n o o f , DEVELOPER NETWORK
G pQ e
Code
ApLeth Lckbutcs
i ' i
vtfan. oi Leadership
Ajax
Widget, v Webservices
inbox <or
-J el c o n i e
J Mai tfW
Widget: l cc Reusable module, C
tnh c p cao vi ng dng
Widget cung cp kh nng c nhn
ha cao vi Website
years i Leadership
6. Ajax, Widget, v Webservices
Weather Widget
Current Conditions
Sunnyvale, CA (94089)
<I52F
Humidity: 61%
Barometer 3003"
Wind: FromMW a16 mph
gusting to HI A mph
Dewpoinfc 39F
Heat Index: 52F ______
Sunlight 5ummarv
http://demos.openrico.org/weather_demo
Web server
Services
APTECH
COMPUTER EDUCATI ON
ApLech ccfcbfitlES
i
(
vtan. oJ Leadership
Weather.com cung cp di ch vu thi ti t \
thng qua mot url bao gm pamer_key
v l i cense_key
A j ax
Widget, v Webservices
http://xoap.weather.com/weather/local/30
339?cc=*&dayf=5&link=xoap&prod=xoap&
par=[PARTNER_KEY]&key=[LICENSE_KEY]
Services
Web server
The
Weather
Channel
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
ApLech ccfcbfitlES
V *
vtars oJ Leadership
Web server
Services
The
Weather
Channel
A j ax
6. Ajax, Widget, v Webservices
cvreather ver= "2.0">
<h ead >< head >
- < l o c i d=' ,3 0 3 3 9 " X ' l o c >
i l n k s tj'p e p n n o ' X l n k s >
<cc>
<l su p >4 27 09 12:55 A M EDT< I sup-
<obst>Dobbi ns ARB- GA < obst>
<tmp >69</tmp >
^f l i k >69< i l i k -
<t>Fair<t>
<i c o n >33< i c on>
t <barx bar>
+ <wiad><iviiid>
<h mi d >62< hmi d>
<v i s >10.0< v i s>
+ <uv>< uv>
<d ew p >56< d
+ <m o o n >< moon>
<C>
<dayf>
<l su p >4 27 09 1:11 A M EDT< l su p>
+ ay d="0" t="Sunday" d t="Apr 2 6 "x d ay >
-*-<day d ="l " t="Monday " d t="Apr d ay >
+ <d ay d ="2" t="Tuesday" d f=' Apr 2SX da> >
+ <d ay d ="3 t= "Wednesday" d t="Apr 29"><d ay
+ -;d ay d =4" t="Thnrsday" d t="Apr 30">< day ?1
< dayfc>
< Tveat her >
Weather.com response
co dinh dang XML
hoac JSON
www. aiti-aptech edu.vn
A plrdl ccfcbfiilES
vtan oi Leadership
Ajax
6. Ajax, Widget, v Webservices
Demo Ajax &
JSON Web service
MakeY!MyHomepage
Y a H o O I t r a v e l
Home Resear ch t r a v el g u id e s Book Deal s My Travel * Themes
SEARCH TRAVEL:
Find It Fast
Search here for cheap airline tickets, hotels, cars cruises and vacations
AVERTI SEMENT
Hotels Cars I Vacations I| Cruises Fl i ghts
(?) Flight Only 0 Flight * Hotel Book together 5 Si
FROM
HAN
Qne-Wav. Multi-City. More...
DEPART RETURN
05/18/09 B ;05/25/09 H jgyyil
Today's Picks forY ahoOOoo ! cOol
Travelingfr.orrr Hanoi, Vietnam I CiiBrge Location | SHOW ME My Recommendat i ons '
Mi ami . FL Cabo San Lucas. Mexi co
Today's Deals
$485 - Riu Ocho Rios all-incl 4-nt trip w/flight
BeachDestinations.com
$98 US flight sale Major Airlines
$87 - Swank Conrad Miami with bay-view
-Yahoo Travel Web Services (Ajax & J SON)-
Keywords :[japan Search
J apan (Kansai)
We landed at Kansai International in the afternoon, and made our way to
Kyoto by the J R limited express train. Too late and too tired to explore the
temples, we walked from Kyoto Station to the hotel passing Higashi
Honganjii. The hotel, Ikoi-no-ie is a small guesthouse I minkishu. with
spotless rooms. J apan doesnt have daylight savings time, so the
sunrise is early. Consequently, we woke up at 5am and walked down to
Toji temple market. On the way we passed Nishi Honganji and walked
under the railroad tracks. The market was just opening as we got there.
The guidebooks we'd read advised us to ...
Yokoso! J apan!
PROLOGUE I ammaking this journal to hopefully' inspire people to grab
their bag and travel around the world This was my first trip alone outside
of Canada, its a hastily planned trip so there were a lot of things that Ive
overlooked like when to go, budget, memory cards, souvenirs - to name a
few. I had no solid iterinary until I got to Matsumoto where I decided to go
Castle hunting. On large cities I stayed in Business Hotels, on smaller
ones in Ryokan (traditional inn)-with private facilities as I wake up early
to beat the crowds. I highly recommend staying in a ryokan. I had no
problem co...
APTECH
COMPUTER EDUCATI ON
WWW. aiti-aptech. edu.vn
vean o Lrjdrrvhip
7. Ajax Toolkits
Thit k v xy dng cc ng dng Ajax vi
Ajax Toolkits
(Frameworks, Libraries...)
< 9
yean. oi Leadership
7. Ajax Toolkits
Bindows
Rich internet Application
Development Framework
moo roofs
Quen/
wr i t * less, do more.
dojo
ASfinet
AJAX
O Ext JS
prototype
YU I Library
DWR
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
years o Leadership
7. Ajax Toolkits
u im ca cc th vin Ajax
S ng gi sn cc phng thc/i tng
S Tng thch trnh duyt (Cross-Browser)
S Gim chi ph pht trin cc ng dng RIA
S H tr cc hiu ng Javascript (animation, drag
s Thao tc vi DOM d dng
7. Ajax Toolkits
Cn xem xt cc yu t kh chn la th vin Ajax
'S H tr Server-driven hay Client driven
'S Giy php m - Open Licensing hay $$$
'S Ti liu h tr, demos
'S Cng ng pht trin
'S Mc abstraction hay highlevel
'S Ngn ng hng ti (C#, PHP, Python, Java)
'S C kh nng pht trin khng.
years oi Leadership
7. Ajax Toolkits
Prototype Library
$('id_of_element') -> document.getElementByld()
$F() -> get Value of element
Try.these()
Ajax.request()
Ajax.Updater()
Element.show/hide/toggle/remove
Object-oriented extensions
APTECH
COMPUTER EDUCATI ON
ytare ui LrjiJ ef ship
7. Ajax Toolkits
X l Ajax Request/Response n gin
f unct i on cr eat eRequest ( ur l ) {
var xhr = new Aj ax. Request ( ur l , {
met hod: 1get 1 f
onCompl et e: showResponse });
}
f unct i on showResponse( xhr ) {
$( ' di v' ) . i nner HTML = xhr . r esponseText ;
}
ytare ui Lrji Jef ship
7. Ajax Toolkits
X l Ajax Request/Response n gin
f unct i on cr eat eRequest ( ur l ) {
var xhr = new Aj ax. Request ( ur l , {
met hod: 1get 1 f
onCompl et e: showResponse });
}
f unct i on showResponse( xhr ) {
$( ' di v' ) . i nner HTML = xhr . r esponseText ;
}
ApLedi LdctHjIc'.
4 r *
<scr i pt sr c="pr ot ot ype . j s" x/ scr i pt >
<scr i pt l anguage=Mj avascr i pt M>
Event . obser ve( wi ndow, ' l oad' , i ni t , f al se) ;
f unct i on i ni t ( ) {
Event . obser ve(' bt nBut t on', ' cl i ck' , makeRequest , f al se) ;
}
f unct i on makeRequest () {
var xhr = new Aj ax.Request (" hel l op. php", {
met hod: ' get ' ,
onCompl et e: showResponse,
par amet er s: {name: $F(' t xt Name' )}
}) ;
}
f unct i on showResponse( xhr ) {
$( ' cont ent ' ) . i nner HTML = xhr . r esponseText ;
}
</ scr i pt >
</ head>
<body>
<i nput t ype="t ext " i d="t xt Name" / >
<i nput t ype="but t on" i d="bt nBut t on" val ue="Send" / >
<di v i d="cont ent "></ di v>
years oi Lrjitkf ship
7. Ajax Toolkits
T ng update n dung
new Aj ax. Updat er ( 1pr oduct s 1 , f / some_ur l ! , {
met hod: 1get 1,
i nser t i on: I nser t i on. Top
}) ;
new Aj ax. Per i odi cal Updat er ( 1pr oduct s 1,
1/ some_ur l 1 , {
met hod: 1get 1,
i nser t i on: I nser t i on. Top,
f req u en cy : If
decay: 2 }) ;
8. Vn v thch thc vi ng dng Ajax
Ajax
Trng thi ng dng Ajax thay i, nhng URL th khng
Lch s trnh duyt, cc dng Navigation (TAB, TREE)
Cc bc trong mt tin trnh
Ngi s dng Confused vi nt Undo
Ti u ha Engine tm kim kh
Bookmark trang web vn
mg xem hin ti
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
APTECH
TM
Sch Ajax
Ajax in Action (Manning)
HeadFirst Ajax (HeadFirst)
Ajax Patterns and Best Practices
(Apress)
Lin kt Web
www.aiaxian.com
http://www.aiaxlessons.com/
http://aiax.phpmagazine.net/
http://aiaxworld.com/
Lin kt Web
http://developer.vahoo.com/
http://code.google.com/apis/aiax/
http://aiaxpatterns.org/
http://www.aiaxmatters.com/
Link mt s th vin ph bin
http://prototypeis.org
http://iauerv.com
Ni dung hi tho:
http://aptechvn. wordpress.com/
ytan odLadenhlp * J 1 r . > ________ A 1 1 ______ 1 1 7
8. Gii thu cc t nguyn tham kho
_ w
years oi Leadership
Demo Ajax with Prototype
APTECH
COMPUTER EDUCATI ON
www. aiti-aptech. edu.vn
yean Leadership