Ajax and PHP John Coggeshall
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
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
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
The basics So, what does AJAX stand for anyway? A synchronous  J avascript  a nd  X ML 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
Asynchronous Javascript AJAX allows us to take advantage of the server for information, 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
Don’t confuse technologies Is AJAX Gmail / Google Maps? No Is AJAX Prototype or Script.aculo.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.0” experience.
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=&quot;JavaScript&quot;> <!-- pic1= new Image(100,25);  pic1.src=&quot;http://example.com/getRandomImage.php&quot;;  //--> </SCRIPT>
“ Traditional” AJAX Despite the misconceptions on what exactly AJAX is, 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.e. onBlur of a zip-code field which automatically finds out the city / state
“ Traditional” AJAX Okay, 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.example.com/getCityState.php?zip=14214 … parse the result … update the city and state input fields to reflect the new information!
Browser Wars Revisited Ah, if only it were that simple Unfortunately, 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
Establishing a Protocol Now that you’ve made a request back to the web server (in this case, 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, each byte representing a command
Establishing a Protocol While there are no standards per-se, 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.php.net/package/json $json_enc = json_encode(array(1,2,3)); $json_dec_var = json_decode(‘{ “abc”:12 }’); javascript:eval(‘{ “abc”:12}’); // return foo.abc in JS
AJAX without XmlHttpRequest Now that you have the basic jist, 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.phpit.net/article/ajax-php-without-xmlhttprequest/2/
I said it was  a synchronous Regardless of the approach you use to generate an AJAX request, 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.. Bad…  BAD
HTTP GET vs. 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
Why I am scared of AJAX
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
One of the biggest problems with AJAX
One of the biggest problems with AJAX Simple requests seem to work just fine…
One of the biggest problems with AJAX
One of the biggest problems with AJAX
One of the biggest problems with AJAX
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
One of the biggest problems with AJAX
One of the biggest problems with AJAX
One of the biggest problems with AJAX
One of the biggest problems with AJAX
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
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.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.roundtwo.com/product/switchproxy Not a true solution, but at least let’s you test for the problem.
AJAX: Redefining the notion of state? Now that we are talking about AJAX intelligently, 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
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…. Clicking reload Closing the window …. Then they’re state is being tracked
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
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
Requests per second (Traditional) Common scaling trick: static content farms Off-load non-logic-based content serving to lightweight and  fast  HTTP servers
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, clearly a new pattern of scaling must be introduced
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
A thought
The Future of AJAX?
Thank you! Questions?

More Related Content

PPT
PHP - Introduction to PHP AJAX
PDF
Basics of JavaScript
PDF
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
PPTX
Introduction to XML
PPT
Java Servlets
PPTX
ASP.NET Page Life Cycle
PDF
Html5-Web-Storage
PPT
javaScript.ppt
PHP - Introduction to PHP AJAX
Basics of JavaScript
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
Introduction to XML
Java Servlets
ASP.NET Page Life Cycle
Html5-Web-Storage
javaScript.ppt

What's hot (20)

PDF
Web scraping in python
PPTX
Introduction to ajax
PPT
Introduction to JavaScript (1).ppt
PPTX
Nodejs functions & modules
PPT
ASP.NET MVC Presentation
PDF
JavaScript - Chapter 12 - Document Object Model
PPTX
Dom(document object model)
PPT
Php Presentation
PPTX
Event In JavaScript
PPTX
Ajax ppt - 32 slides
PDF
Introduction to Redux
PPTX
Introduction to Spring Boot
PPT
Php with MYSQL Database
PPT
PPTX
Ajax
PPTX
Ajax presentation
PPTX
Lesson 6 php if...else...elseif statements
PDF
JavaScript Promises
Web scraping in python
Introduction to ajax
Introduction to JavaScript (1).ppt
Nodejs functions & modules
ASP.NET MVC Presentation
JavaScript - Chapter 12 - Document Object Model
Dom(document object model)
Php Presentation
Event In JavaScript
Ajax ppt - 32 slides
Introduction to Redux
Introduction to Spring Boot
Php with MYSQL Database
Ajax
Ajax presentation
Lesson 6 php if...else...elseif statements
JavaScript Promises
Ad

Similar to Ajax and PHP (20)

PPT
jQuery Ajax
PDF
Ajax
PDF
Ajax
PDF
1 ppt-ajax with-j_query
PPTX
AJAX.pptx
PPT
01 Ajax Intro
PPT
AJAX
PPT
Using Ajax In Domino Web Applications
PPT
PPT
PPTX
Ajax for dummies, and not only.
PPT
DOCX
Copy of ajax tutorial
PPT
AJAX.ppt
PPT
PPT
Web Programming using Asynchronous JavaX
jQuery Ajax
Ajax
Ajax
1 ppt-ajax with-j_query
AJAX.pptx
01 Ajax Intro
AJAX
Using Ajax In Domino Web Applications
Ajax for dummies, and not only.
Copy of ajax tutorial
AJAX.ppt
Web Programming using Asynchronous JavaX
Ad

More from John Coggeshall (20)

PPTX
Virtualization for Developers
PPTX
Migrating to PHP 7
PPTX
Peek at PHP 7
PPTX
ZF2 Modules: Events, Services, and of course, modularity
PPT
PHP Development for Google Glass using Phass
PPTX
Virtualization for Developers
PPTX
Development with Vagrant
PPTX
Introduction to Zend Framework 2
PPTX
10 things not to do at a Startup
PPTX
Virtualization for Developers
PPTX
PPT
Building PHP Powered Android Applications
PPT
Ria Applications And PHP
PPT
Beyond the Browser
PPT
Apache Con 2008 Top 10 Mistakes
PPT
Ria Development With Flex And PHP
PPT
Top 10 Scalability Mistakes
PPT
Enterprise PHP: A Case Study
PPT
Building Dynamic Web Applications on i5 with PHP
PPT
PHP Security Basics
Virtualization for Developers
Migrating to PHP 7
Peek at PHP 7
ZF2 Modules: Events, Services, and of course, modularity
PHP Development for Google Glass using Phass
Virtualization for Developers
Development with Vagrant
Introduction to Zend Framework 2
10 things not to do at a Startup
Virtualization for Developers
Building PHP Powered Android Applications
Ria Applications And PHP
Beyond the Browser
Apache Con 2008 Top 10 Mistakes
Ria Development With Flex And PHP
Top 10 Scalability Mistakes
Enterprise PHP: A Case Study
Building Dynamic Web Applications on i5 with PHP
PHP Security Basics

Recently uploaded (20)

PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
DOCX
search engine optimization ppt fir known well about this
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Hybrid model detection and classification of lung cancer
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Architecture types and enterprise applications.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
A comparative study of natural language inference in Swahili using monolingua...
Hindi spoken digit analysis for native and non-native speakers
Assigned Numbers - 2025 - Bluetooth® Document
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Web Crawler for Trend Tracking Gen Z Insights.pptx
search engine optimization ppt fir known well about this
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
observCloud-Native Containerability and monitoring.pptx
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
DP Operators-handbook-extract for the Mautical Institute
Taming the Chaos: How to Turn Unstructured Data into Decisions
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
A contest of sentiment analysis: k-nearest neighbor versus neural network
Developing a website for English-speaking practice to English as a foreign la...
Hybrid model detection and classification of lung cancer
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Architecture types and enterprise applications.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf

Ajax and PHP

  • 1. Ajax and PHP John Coggeshall
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. The basics So, what does AJAX stand for anyway? A synchronous J avascript a nd X ML 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
  • 6. Asynchronous Javascript AJAX allows us to take advantage of the server for information, 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
  • 7. Don’t confuse technologies Is AJAX Gmail / Google Maps? No Is AJAX Prototype or Script.aculo.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.0” experience.
  • 8. 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=&quot;JavaScript&quot;> <!-- pic1= new Image(100,25); pic1.src=&quot;http://example.com/getRandomImage.php&quot;; //--> </SCRIPT>
  • 9. “ Traditional” AJAX Despite the misconceptions on what exactly AJAX is, 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.e. onBlur of a zip-code field which automatically finds out the city / state
  • 10. “ Traditional” AJAX Okay, 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.example.com/getCityState.php?zip=14214 … parse the result … update the city and state input fields to reflect the new information!
  • 11. Browser Wars Revisited Ah, if only it were that simple Unfortunately, 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
  • 12. Establishing a Protocol Now that you’ve made a request back to the web server (in this case, 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, each byte representing a command
  • 13. Establishing a Protocol While there are no standards per-se, 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.php.net/package/json $json_enc = json_encode(array(1,2,3)); $json_dec_var = json_decode(‘{ “abc”:12 }’); javascript:eval(‘{ “abc”:12}’); // return foo.abc in JS
  • 14. AJAX without XmlHttpRequest Now that you have the basic jist, 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.phpit.net/article/ajax-php-without-xmlhttprequest/2/
  • 15. I said it was a synchronous Regardless of the approach you use to generate an AJAX request, 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.. Bad… BAD
  • 16. HTTP GET vs. 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
  • 17. Why I am scared of AJAX
  • 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
  • 19. One of the biggest problems with AJAX
  • 20. One of the biggest problems with AJAX Simple requests seem to work just fine…
  • 21. One of the biggest problems with AJAX
  • 22. One of the biggest problems with AJAX
  • 23. One of the biggest problems with AJAX
  • 24. 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
  • 25. One of the biggest problems with AJAX
  • 26. One of the biggest problems with AJAX
  • 27. One of the biggest problems with AJAX
  • 28. One of the biggest problems with AJAX
  • 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
  • 30. 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.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.roundtwo.com/product/switchproxy Not a true solution, but at least let’s you test for the problem.
  • 31. AJAX: Redefining the notion of state? Now that we are talking about AJAX intelligently, 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
  • 32. 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…. Clicking reload Closing the window …. Then they’re state is being tracked
  • 33. 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
  • 34. 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
  • 35. Requests per second (Traditional) Common scaling trick: static content farms Off-load non-logic-based content serving to lightweight and fast HTTP servers
  • 36. 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, clearly a new pattern of scaling must be introduced
  • 37. 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
  • 39. The Future of AJAX?