You are on page 1of 40

Ajax and PHP

John Coggeshall

Copyright © 2006, Zend Technologies Inc.

Welcome!
‡ Who am I: John Coggeshall 
   
Sr. Technical Consultant, Zend Technologies Author PHP 5 Unleashed Zend Educational Advisory Board Speaker on PHP-related topics worldwide Geek

Oct. 18, 2005

#2

Why are we here?
‡ We·re here to discuss AJAX 
  
« and PHP « and XML « and Javascript « and Networks

‡ In this three hour tutorial, I·ll be explaining a
number of AJAX-related concepts

Oct. 18, 2005

#3

Fair Warning
‡ I·ll warn you right now ² I work for Zend, not Netscape 
I am not a client-side developer  I do not know which browsers support which constructs of
Javascript under which conditions using which technologies on which operating system  I am a PHP developer responsible for scaling numerous mission-critical PHP sites and technologies  I do understand Internet architectures and how to scale them in practical environments  I do understand enough about AJAX as a technology to speak intelligently 

Don·t expect a lot of flashy AJAX demos here

Oct. 18, 2005

#4

2005 #5 .The basics ‡ So. what does AJAX stand for anyway?  Asynchronous Javascript and XML ‡ The basic idea:  Javascript is the reigning champion of the client side ‡ Image roll-overs ‡ DHTML ‡ Client-side form processing  Not all information and processes can be given to the client ‡ Insecure / Untrusted ‡ Simple processing ability restrictions Oct. 18.

while leaving the GUI-related items to the client ‡ It·s not a new technology  Just has a neat acronym now ‡ How·s it work?  Javascript applications perform requests to the server using an agreed protocol  The server responds in kind with the requested information  All of this takes place without reloading the page ‡ Asynchronous of the client  Javascript then processes the result and manipulates the page Oct.Asynchronous Javascript ‡ AJAX allows us to take advantage of the server for information. 18. 2005 #6 .

0µ experience.Don·t confuse technologies ‡ Is AJAX Gmail / Google Maps?  No ‡ Is AJAX Prototype or Script. 18.us?  No ‡ Is AJAX Ruby-on-Rails?  No AJAX is simply the idea of enabling your browser to communicate asynchronously with the server to provide a more rich user ´Web 2.aculo. Oct. 2005 #7 .

com/getRandomImage.25). 2005 #8 .php". 18. pic1.src="http://example.Implementing AJAX ‡ Step 1: Open a asynchronous connection from the client to the server ‡ Step 2: Perform a request against the server using an agreed upon protocol ‡ Step 3: Process the results via Javascript and manipulate the client without causing a full refresh of the page <SCRIPT language="JavaScript"> <!-pic1= new Image(100. //--> </SCRIPT> Oct.

e. 18. it does have a traditional approach  XMLHttpRequest object ‡ Available in most modern browsers ‡ Identical in concept to the Image object  Allows you to retrieve data from the server without performing an entirely new request ‡ Requests are generally made in conjunction with a particular Javascript event  i. onBlur of a zip-code field which automatically finds out the city / state Oct. 2005 #9 .´Traditionalµ AJAX ‡ Despite the misconceptions on what exactly AJAX is.

18. so here we go: ‡ ‡ ‡ ‡  <input type=´textµ size=´5µ onBlur=´updateCityState()µ> Now all we need to do is implement a javascript updateCityState() function that creates an XMLHttpRequest object Then we take that object and request a PHP page http://www. 2005 # 10 .php?zip=14214 «parse the result «update the city and state input fields to reflect the new information! Oct.com/getCityState.example.´Traditionalµ AJAX ‡ Okay.

Browser Wars Revisited ‡ Ah. 18. XMLHttpRequest is implemented in different ways on each browser  Requires lots of Javascript black-magic that I don·t know to ensure you·re creating the proper object the proper way ‡ My solution: Google  This problem has been solved a million times over so I won·t re-explain the wheel here Oct. 2005 # 11 . if only it were that simple  Unfortunately.

18. 2005 # 12 . using PHP and HTTP GET) time to deal with the response  This is where things really go amuck ‡ There is no standard AJAX protocol. the data can be anything       Comma separated fields Serialized Javascript Custom XML SOAP URLEncoded fields 20 bytes of data.Establishing a Protocol ‡ Now that you·ve made a request back to the web server (in this case. each byte representing a command Oct.

there are common techniques  Future versions of PHP will support JSON encoding by default  Allows you to pass complex data types back and forth between PHP and Javascript fairly easily  You can download JSON encoding support from PECL ‡ ‡ ‡ ‡ http://pecl. // return foo. javascript:eval(¶{ ´abcµ:12}·).Establishing a Protocol ‡ While there are no standards per-se.2. 18. 2005 # 13 .php.abc in JS Oct.3)). $json_dec_var = json_decode(¶{ ´abcµ:12 }·).net/package/json $json_enc = json_encode(array(1.

the cleaver among you must realize that XmlHttpRequest isn·t necessary ‡ With some crafty HTML you can do your AJAX request using ´standardµ browser facilities  Step 1: Use Javascript to create a new <SCRIPT> tag in the document  Set the source of this script tag dynamically to our PHP backend URL and provide the ´output elementµ ID we are interested in manipulating  Have our backend written in PHP process the request and return Javascript manipulating that ID as we saw fit. ‡ http://www. 2005 # 14 . 18.phpit.net/article/ajax-php-withoutxmlhttprequest/2/ Oct.AJAX without XmlHttpRequest ‡ Now that you have the basic jist.

I said it was asynchronous ‡ Regardless of the approach you use to generate an AJAX request.. 2005 # 15 . Bad« BAD Oct. 18. always remember that it is an ASYNCHRNONOUS request.  Performing a behind the scenes synchronous request stands a very good chance of locking up IE  Every second the server takes the respond to the client in a synchronous request is a second the browser is not responding to input  Bad.

18.HTTP GET vs. 2005 # 16 . POST ‡ This one personally really urkes me about web developers  GET is for GETTING data  POST is for POSTING data ‡ Sending a GET request should never cause an update on the server  Reason 1: GET requests should be bookmark-able  Reason 2: GET requests should be cache-able ‡ If you use AJAX for anything other then retrieving data then use HTTP POST for those actions Oct.

Zend Technologies Inc. .Why I am scared of AJAX Copyright © 2006.

2005 # 18 .One of the biggest problems with AJAX ‡ Let·s imagine that each request sent over the wire is like a car driving from point A (the client) to point B (the server) ‡ Roads are Networks Oct. 18.

18. 2005 # 19 .One of the biggest problems with AJAX Oct.

One of the biggest problems with AJAX ‡ Simple requests seem to work just fine« Oct. 18. 2005 # 20 .

2005 # 21 .One of the biggest problems with AJAX Oct. 18.

18. 2005 # 22 .One of the biggest problems with AJAX Oct.

18.One of the biggest problems with AJAX Oct. 2005 # 23 .

One of the biggest problems with AJAX ‡ The problem with AJAX has to do with multiple dependent asynchronous requests  You can·t rely on any order of operations in classical AJAX models Oct. 18. 2005 # 24 .

2005 # 25 . 18.One of the biggest problems with AJAX Oct.

2005 # 26 . 18.One of the biggest problems with AJAX Oct.

2005 # 27 .One of the biggest problems with AJAX Oct. 18.

One of the biggest problems with AJAX Oct. 18. 2005 # 28 .

2005 # 29 .Some requests will happen faster ‡ When working with AJAX. always know you cannot rely on one request finishing before the next is triggered ‡ Requests can take different lengths of time based on a huge array of factors  Server load and Network load come to mind ‡ Can really mess up your application ‡ Bad news: None of the current AJAX toolkits account for this latency Oct. 18.

18. but at least let·s you test for the problem.com/archives/2005/08/08/ajax-proxy-02 ‡ Allows you to simulate latency in your requests  You can use it in conjunction with ´SwitchProxyµ to point your browser at a different proxy server to use it ‡ http://www. Oct.com/product/switchproxy ‡ Not a true solution. 2005 # 30 .roundtwo.Developing with Latency in mind ‡ A number of tools exist for developing AJAX applications with latency in mind  AJAX Proxy is a good example ‡ http://ajaxblog.

AJAX: Redefining the notion of state? ‡ Now that we are talking about AJAX intelligently. 18. 2005 # 31 . let·s talk about a very important aspect to the modern web application: sessions  Sessions allow current web applications to maintain state across stateless HTTP requests Oct.

Then they·re state is being tracked Oct.Throw cookies away? ‡ In AJAX models. these session cookies are no longer necessary  In-memory data received from the server during an AJAX request is state  Lends itself much more to the classical MVC / Messaging model of client-side applications  As long as the user doesn·t ´closeµ the application«. 18. ‡ Clicking reload ‡ Closing the window  «. 2005 # 32 .

Requests per second (Traditional) ‡ Other then actually working. scaling a web application is the most important architectural consideration  (accurate) Requests per second is key metric ‡ Consider what happens during a single server/single client exchange Oct. 18. 2005 # 33 .

18.Requests per second (Traditional) ‡ Servers are limited to a maximum requests per second by numerous factors ‡ To scale:  Make the maximum sustainable RPS number as high as possible ‡ Faster script execution times ‡ Faster database access  Make the most of every request ‡ Avoid costly unnecessary handshakes ‡ Intelligently segment content Oct. 2005 # 34 .

2005 # 35 . 18.Requests per second (Traditional) ‡ Common scaling trick: static content farms  Off-load non-logic-based content serving to lightweight and fast HTTP servers Oct.

18. 2005 # 36 . clearly a new pattern of scaling must be introduced Oct.Requests per second (AJAX) ‡ Looking at the AJAX philosophy it·s clear a different request pattern exists  Relatively heavy and common load spikes  Very frequent and relatively quick follow-up requests ‡ While some tricks can be borrowed from the old models.

Optimizing AJAX pages ‡ Single-serve client libraries  Use tools to combine multiple JavaScript/CSS files into a single giant file to reduce the load on the server to a single request to load the application logic ‡ Can be cached on the client ‡ Avoid first-execution spikes  Design your applications upon initial execution to perform a single AJAX request to effectively populate the entire page ‡ Reduces strain on both the pipeline and on your backend database servers Oct. 2005 # 37 . 18.

2005 # 38 .A thought Oct. 18.

The Future of AJAX? Copyright © 2006. Zend Technologies Inc. .

Zend Technologies Inc. .Thank you! Questions? Copyright © 2006.