INP AJAX, JSON, frameworks 1
Upcoming SlideShare
Loading in...5
×
 

INP AJAX, JSON, frameworks 1

on

  • 1,016 views

 

Statistics

Views

Total Views
1,016
Views on SlideShare
1,016
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

INP AJAX, JSON, frameworks 1 INP AJAX, JSON, frameworks 1 Document Transcript

  • INP AJAX – the basic idea Internet programming 2009/2010 • One of the main problems in webapplications is the page based request AJAX, JSON, • Asynchronous JavaScript And XML (AJAX) tries frameworks to solve this • Basic idea • Exchange small amounts of data with the server behind the scenes, while on the page • Therefore, no need to reload the entire page each time the user makes a change • Increases interactivity, speed and usability 1 2 AJAX is nothing new… (1) AJAX is nothing new… (2) • AJAX is a combination of • AJAX is not a technology in itself • XHTML and CSS for mark-up and styling information • Like DHTML and LAMP, it's a group of other (already existing) technologies that are used in combination • The DOM accessed with JavaScript to dynamically • The main enabling component has been around display and interact with the information presented in (some) browsers since 1998 • The XMLHttpRequest object to exchange data • XMLHttpRequest asynchronously with the web server • It was not until Google started using it in a.o. • XML as the format for transferring data back from Google Earth (retrieving map data) and it was the server given a distinctive name that it became popular 3 4 AJAX philosophy (1) AJAX philosophy (2) • Webpages, unlike desktop applications, are • Using AJAX, webpage (application) and data loosely coupled can once more become tightly coupled • Data they display is not tightly bound to data • AJAX enables you to build desktop like sources and must be first put into an HTML client/server applications according to the page format before they can be presented traditional paradigm you're familiar with • Webpages thus have to be re-loaded each time a user needs to view different datasets • AJAX signals the coming of age of DHTML • Finally a mature client side application paradigm • Getting used to this new paradigm and its exists for the web limitations is one of the challenges of Internet programming • Remember old skool Java Applets? 5 6 AJAX, JSON, frameworks 1
  • INP AJAX philosophy (3) AJAX examples on the web • Your application now more or less becomes one • Google Suggest or more JavaScript applications, talking to a (PHP) back-end, possibly with database access • Google Maps • Note that AJAX is a client side technology, • Prototype / Scriptaculous inpendent of server software and supported by most browsers in a more or less uniform way • Thickbox • You may start using it today! • Gmail / Live Mail • AJAX is by many considered to be a mandatory part of any "Web 2.0" application • Protopage 7 8 AJAX example (1) AJAX example (2) <html> <head> <script src="selectuser.js"></script> </head> <body> <form>Select a User: <select name="users" onchange="showUser(this.value) "> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> id FirstName LastName Age Hometown Job <option value="3">Glenn Quagmire</option> 1 Peter Griffin 41 Quahog Brewery </select> </form> 2 Lois Griffin 40 Newport Piano Teacher <p> 3 Joseph Swanson 39 Quahog Police Officer <div id="txtHint"><b>User info will be listed here. </b></div> </p> 4 Glenn Quagmire 41 Quahog Pilot </body> </html> 9 10 AJAX example (3) AJAX example (4) var xmlHttpfunction showUser(str) { function stateChanged() { if (xmlHttp.readyState==4) { xmlHttp=GetXmlHttpObject() document.getElementById("txtHint").innerHTML= xmlHttp.responseText if (xmlHttp==null) { } alert ("Browser does not support HTTP Request") } return } var url="getuser.php" url=url+"?q="+str url=url+"&sid="+Math.random() xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } 11 12 AJAX, JSON, frameworks 2
  • INP AJAX example (5) AJAX example (6) function GetXmlHttpObject() { <?php var xmlHttp=null; $q=$_GET["q"]; $con = mysql_connect('localhost', 'lennart', 'gehei m'); try { mysql_select_db("ajax_demo", $con); // IE7+, Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); $sql="SELECT * FROM user WHERE id = '".$q."'"; } $result = mysql_query($sql); catch (e) { echo "<table border='1'>”; // IE6, IE5.5 ... try { while($row = mysql_fetch_array($result)) { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; } echo "<td>" . $row['LastName'] . "</td>"; catch (e) { ... xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); echo "</tr>"; } } echo "</table>"; } return xmlHttp; mysql_close($con); } ?> 13 14 AJAX (dis)advantages AJAX odds & ends (1) • Interactivity, responsiveness, fluidity • Other technologies than JavaScript, • Portability XMLHttpRequest and XML are possible • AJAX fills the niche left behind by Java Applets: • Other client side scripting languages may be used extending the browser with lightweight mini- • IFrame object may be used instead of the applications XMLHttpRequest object to exchange data with the • Usability (back-button, bookmarks) web server, or even dynamically added <script> tags • Think about when to render a new page • Preformatted HTML, plain text or JSON may be used • Response-time instead of XML (as in the example) • Need for JavaScript • Most important is the idea of asynchronous • Accessibility communication between client and server 15 16 AJAX odds & ends (2) AJAX odds & ends (3) • AJAX can be used for validation, which is now • Other derivative technologies, based on AJAX, entirely server side based are already appearing • Security may be an issue • AFLAX (Asynchronous Flash and XML) • AJAX can be used for two-way data transfers • AJAX on Rails (Ruby on Rails with AJAX support) • State may be divided between client/server • Note the role of CSS and DOM in displaying/ • Working with AJAX requires hiding content and the importance of their • Writing custom JavaScript that directly uses the more mature cross-browser/platform support XMLHttpRequest object's API • AJAX means that there is no longer any • AJAX JavaScript library (Feather Ajax, xajax, …) justification for not enabling JavaScript (but…) 17 18 AJAX, JSON, frameworks 3
  • INP AJAX libraries/exchange formats Prototype example • Basic functionality is easily implemented ... <script src="prototype.js" language="JavaScript" type="text/javascript"></script> yourself directly, without using libraries ... var value1 = $F('name_of_id_1'); • Complex functionality often requires complex var value2 = $F('name_of_id_2'); var url = 'http://yourserver/path/server_script'; data structures and therefore complex data var pars = 'value1=' + value1 + '&value2=' + handling (libraries) and complex exchange value2; formats (XML, JSON) var myAjax = new Ajax.Request( url, { method: 'post', • Several libraries and exchange formats may parameters: pars, onComplete: showResponse be used in the final assignment }); 19 ... 20 xajax (1) xajax (2) • xajax is an open source PHP class library • “The xajax PHP object generates JavaScript wrapper functions for the PHP functions you want to be able to call implementation of AJAX asynchronously from your application. When called, these • Applications developed with xajax can wrapper functions use JavaScript's XMLHttpRequest object to asynchronously communicate with the xajax object on the asynchronously call server-side PHP functions server which calls the corresponding PHP functions. Upon and update content without reloading the page. completion, an xajax XML response is returned from the PHP functions, which xajax passes back to the application. The • xajax requires no prior knowledge of JavaScript XML response contains instructions and data that are parsed • xajax requires using XML as exchange format by xajax's JavaScript message pump and used to update the content of your application.” 21 22 xajax (3) xajax example (1) • Seven simple steps <?php require_once ("../xajax.inc.php"); • Include the xajax class library in your PHP code $xajax = new xajax("multiply.server.php"); • Instantiate the xajax object in your PHP code $xajax->registerFunction("multiply"); • Register the names of the PHP functions you want to be ?> multiply.common.php able to call through xajax in your PHP code <?php • Write the PHP functions and use the xajaxResponse object function multiply($x, $y) to return XML commands from them in your PHP code { $objResponse = new xajaxResponse(); • Before your script sends any output, have xajax handle any $objResponse->addAssign("z", "value", $x*$y); requests in your PHP code return $objResponse; } • Tell xajax to generate the necessary JavaScript from PHP • Call the function from a JavaScript event or function in your require("multiply.common.php"); client side application $xajax->processRequests(); ?> multiply.server.php 23 24 AJAX, JSON, frameworks 4
  • INP xajax example (2) JSON <?php require("multiply.common.php");?> • JavaScript Object Notation <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi tional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona l.dtd"> • A text-based, human-readable format for <html> <head> representing objects and other data structures <title>xajax Multiplier</title> <?php $xajax->printJavascript('../'); ?> • Mainly used to transmit such structured data </head> <body> over a network connection, notably in the <input type="text" name="x" id="x" value="2" size=" /> * 3" context of AJAX <input type="text" name="y" id="y" value="3" size=" /> = 3" <input type="text" name="z" id="z" value="" size="3 /> " • As an alternative to XML, preformatted HTML or <input type="button" value="Calculate“ onclick="xajax_multiply(document.getElementById('x' ).value, plain text document.getElementById('y').value);return false;" /> </body> • A Subset of JavaScript's object literal notation </html> multiply.php 25 • Security may be an issue 26 JSON example Using JSON for AJAX { var the_object; "firstName": "John", var http_request = new XMLHttpRequest(); "lastName": "Smith", http_request.open("GET", url, true); "address": { http_request.onreadystatechange = function () { "city": "New York, NY", if (http_request.readyState == 4) { "zipCode": 10021, if (http_request.status == 200) { "streetAddress": "21 2nd Street" the_object = eval("(" + http_request.responseText }, + ")"); "phoneNumbers": [ } else { "212 732-1234", alert("There was a problem with the URL."); "646 123-4567" } ] http_request = null; } } }; http_request.send(null); var p = eval("(" + JSON_text + ")"); 27 28 Where we are now Programming webapplications • We've seen several common internet • Programming webapplications is a lot of work! programming technologies • Reinventing the wheel again and again • CGI, JavaScript, CSS, DOM, PHP, Java Servlets, • Handling form data, input validation, database Perl, XML, XSLT, AJAX, … access, session management, security and • We've mostly taken a quite basic "feet in the authentication, … mud" approach to these technologies • Basically, it's all about accessing your data • Build up your application from scratch • View, insert, update, delete through a nice interface • Use little or none external add-ons • Could we abstract from most of the "boring" issues? • Many other technologies exist and evolve • Use a framework! • Let's have a look at yet another popular one 29 • Evolution is often geared towards this aspect 30 AJAX, JSON, frameworks 5
  • INP Webapplication frameworks Examples of frameworks • A set of software tools to facilitate fast and • DBI (Library, Perl based) easy web application development • PEAR (Library, PHP based) • Typically provide functionality such as • Smarty (Presentation, PHP based) • Database access • ZK (Presentation, Java/AJAX based) • Templating • Django (MVC, Python based) • Session management • Ruby on Rails (MVC, Ruby based) • Security (authentication, input validation) • CakePHP (MVC, Ruby based) • Range from simple libraries to presentation • Codeigniter (MVC, PHP based) mechanisms to complete systems using the • WebObjects (Apple proprietary, Java based) Model-View-Controller concept (MVC) • … 31 32 Model-View-Controller (1) Model-View-Controller (2) • Software architecture • Model • Separates application's • The domain-specific representation of the information on which the application operates • Data model • View • User interface • Renders the model into a form suitable for • Control logic interaction, typically a user interface element (HTML for example) • Modification to one • Controller component are possible • Responds to events, typically user actions, and with minimal impact on invokes changes on the model and perhaps the other components 33 view 34 Model-View-Controller (3) Model-View-Controller (4) • Many applications use a persistent storage 1. The user interacts with the user interface in some way (e.g., user presses a button) mechanism (such as a database) to store data 2. A controller handles the input event from the user • In MVC it is understood to be underneath or interface, often via a registered handler or callback encapsulated by the Model 3. The controller accesses the model, possibly updating it in a way appropriate to the user's action (e.g., controller • In web context updates user's shopping cart) (basic interpretation) 4. A view uses the model to generate an appropriate user interface (e.g., view produces a screen listing the shopping • Database / db access layer cart contents); the view gets its own data from the model • Template / HTML 5. The user interface waits for further user interactions, which • Script begins the cycle anew 35 36 AJAX, JSON, frameworks 6
  • INP Framework disadvantages • Most frameworks force you into their somewhat rigid approach • A Right Way to do things • Websites look and work similar • Extensions are sometimes possible • These may be difficult or tiresome to implement • Flexibility versus complexity tradeoff 37 AJAX, JSON, frameworks 7