+ All Categories
Home > Documents > INP AJAX, JSON, frameworks 1

INP AJAX, JSON, frameworks 1

Date post: 01-Nov-2014
Category:
Upload: sampetruda
View: 1,065 times
Download: 2 times
Share this document with a friend
Description:
 
7
INP AJAX, JSON, frameworks 1 1 Internet programming 2009/2010 AJAX, JSON, frameworks 2 AJAX – the basic idea One of the main problems in webapplications is the page based request Asynchronous JavaScript And XML (AJAX) tries 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 3 AJAX is nothing new… (1) AJAX is a combination of XHTML and CSS for mark-up and styling information The DOM accessed with JavaScript to dynamically display and interact with the information presented The XMLHttpRequest object to exchange data asynchronously with the web server XML as the format for transferring data back from the server 4 AJAX is nothing new… (2) AJAX is not a technology in itself Like DHTML and LAMP, it's a group of other (already existing) technologies that are used in combination The main enabling component has been around in (some) browsers since 1998 XMLHttpRequest It was not until Google started using it in a.o. Google Earth (retrieving map data) and it was given a distinctive name that it became popular 5 AJAX philosophy (1) Webpages, unlike desktop applications, are loosely coupled Data they display is not tightly bound to data sources and must be first put into an HTML page format before they can be presented Webpages thus have to be re-loaded each time a user needs to view different datasets Getting used to this new paradigm and its limitations is one of the challenges of Internet programming 6 AJAX philosophy (2) Using AJAX, webpage (application) and data can once more become tightly coupled AJAX enables you to build desktop like client/server applications according to the traditional paradigm you're familiar with AJAX signals the coming of age of DHTML Finally a mature client side application paradigm exists for the web Remember old skool Java Applets?
Transcript
Page 1: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 1

1

Internet programming 2009/2010

AJAX, JSON,

frameworks

2

AJAX – the basic idea

• One of the main problems in webapplications is the page based request

• Asynchronous JavaScript And XML (AJAX) tries 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

3

AJAX is nothing new… (1)

• AJAX is a combination of

• XHTML and CSS for mark-up and styling information

• The DOM accessed with JavaScript to dynamically

display and interact with the information presented

• The XMLHttpRequest object to exchange data

asynchronously with the web server

• XML as the format for transferring data back from

the server

4

AJAX is nothing new… (2)

• AJAX is not a technology in itself

• Like DHTML and LAMP, it's a group of other (already

existing) technologies that are used in combination

• The main enabling component has been around

in (some) browsers since 1998

• XMLHttpRequest

• It was not until Google started using it in a.o.

Google Earth (retrieving map data) and it was

given a distinctive name that it became popular

5

AJAX philosophy (1)

• Webpages, unlike desktop applications, are loosely coupled

• Data they display is not tightly bound to data sources and must be first put into an HTML page format before they can be presented

• Webpages thus have to be re-loaded each time a user needs to view different datasets

• Getting used to this new paradigm and its limitations is one of the challenges of Internet programming

6

AJAX philosophy (2)

• Using AJAX, webpage (application) and data

can once more become tightly coupled

• AJAX enables you to build desktop like

client/server applications according to the

traditional paradigm you're familiar with

• AJAX signals the coming of age of DHTML

• Finally a mature client side application paradigm

exists for the web

• Remember old skool Java Applets?

Page 2: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 2

7

AJAX philosophy (3)

• Your application now more or less becomes one

or more JavaScript applications, talking to a

(PHP) back-end, possibly with database access

• Note that AJAX is a client side technology,

inpendent of server software and supported by

most browsers in a more or less uniform way

• You may start using it today!

• AJAX is by many considered to be a mandatory

part of any "Web 2.0" application8

AJAX examples on the web

• Google Suggest

• Google Maps

• Prototype / Scriptaculous

• Thickbox

• Gmail / Live Mail

• Protopage

9

AJAX example (1)

PilotQuahog41QuagmireGlenn4

Police OfficerQuahog39SwansonJoseph3

Piano TeacherNewport40GriffinLois2

BreweryQuahog41GriffinPeter1

JobHometownAgeLastNameFirstNameid

10

<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><option value="3">Glenn Quagmire</option></select></form><p><div id="txtHint"><b>User info will be listed here. </b></div></p></body></html>

AJAX example (2)

11

AJAX example (3)

var xmlHttpfunction showUser(str) {

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null) {alert ("Browser does not support HTTP Request")return

}

var url="getuser.php"url=url+"?q="+strurl=url+"&sid="+Math.random()

xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)

}12

AJAX example (4)

function stateChanged() { if (xmlHttp.readyState==4) {

document.getElementById("txtHint").innerHTML=xmlHttp.responseText

} }

Page 3: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 3

13

AJAX example (5)

function GetXmlHttpObject() {var xmlHttp=null;try {

// IE7+, Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();

}catch (e) {

// IE6, IE5.5try {

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e) {

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

}return xmlHttp;

}14

AJAX example (6)

<?php$q=$_GET["q"];$con = mysql_connect('localhost', 'lennart', 'gehei m');mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";$result = mysql_query($sql);

echo "<table border='1'>”;...

while($row = mysql_fetch_array($result)) {echo "<tr>";echo "<td>" . $row['FirstName'] . "</td>";echo "<td>" . $row['LastName'] . "</td>";...

echo "</tr>";}echo "</table>";

mysql_close($con);?>

15

AJAX (dis)advantages

• Interactivity, responsiveness, fluidity

• Portability

• AJAX fills the niche left behind by Java Applets: extending the browser with lightweight mini-applications

• Usability (back-button, bookmarks)

• Think about when to render a new page

• Response-time

• Need for JavaScript

• Accessibility16

AJAX odds & ends (1)

• Other technologies than JavaScript, XMLHttpRequest and XML are possible

• Other client side scripting languages may be used

• IFrame object may be used instead of the XMLHttpRequest object to exchange data with the web server, or even dynamically added <script> tags

• Preformatted HTML, plain text or JSON may be used instead of XML (as in the example)

• Most important is the idea of asynchronous communication between client and server

17

AJAX odds & ends (2)

• AJAX can be used for validation, which is now entirely server side based

• Security may be an issue

• AJAX can be used for two-way data transfers

• State may be divided between client/server

• Note the role of CSS and DOM in displaying/ hiding content and the importance of their more mature cross-browser/platform support

• AJAX means that there is no longer any justification for not enabling JavaScript (but…)

18

AJAX odds & ends (3)

• Other derivative technologies, based on AJAX,

are already appearing

• AFLAX (Asynchronous Flash and XML)

• AJAX on Rails (Ruby on Rails with AJAX support)

• Working with AJAX requires

• Writing custom JavaScript that directly uses the

XMLHttpRequest object's API

• AJAX JavaScript library (Feather Ajax, xajax, …)

Page 4: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 4

19

AJAX libraries/exchange formats

• Basic functionality is easily implemented

yourself directly, without using libraries

• Complex functionality often requires complex

data structures and therefore complex data

handling (libraries) and complex exchange

formats (XML, JSON)

• Several libraries and exchange formats may

be used in the final assignment

20

Prototype example

...

<script src="prototype.js" language="JavaScript" type="text/javascript"></script>

...

var value1 = $F('name_of_id_1');var value2 = $F('name_of_id_2');var url = 'http://yourserver/path/server_script';var pars = 'value1=' + value1 + '&value2=' + value2;

var myAjax = new Ajax.Request(url, {

method: 'post', parameters: pars, onComplete: showResponse

});

...

21

xajax (1)

• xajax is an open source PHP class library

implementation of AJAX

• Applications developed with xajax can

asynchronously call server-side PHP functions

and update content without reloading the page.

• xajax requires no prior knowledge of JavaScript

• xajax requires using XML as exchange format

22

xajax (2)

• “The xajax PHP object generates JavaScript wrapper

functions for the PHP functions you want to be able to call

asynchronously from your application. When called, these

wrapper functions use JavaScript's XMLHttpRequest object to

asynchronously communicate with the xajax object on the

server which calls the corresponding PHP functions. Upon

completion, an xajax XML response is returned from the PHP

functions, which xajax passes back to the application. The

XML response contains instructions and data that are parsed

by xajax's JavaScript message pump and used to update the

content of your application.”

23

xajax (3)

• Seven simple steps• Include the xajax class library in your PHP code

• Instantiate the xajax object in your PHP code

• Register the names of the PHP functions you want to be able to call through xajax in your PHP code

• Write the PHP functions and use the xajaxResponse object

to return XML commands from them in your PHP code

• Before your script sends any output, have xajax handle any requests in your PHP code

• Tell xajax to generate the necessary JavaScript from PHP

• Call the function from a JavaScript event or function in your

client side application

24

xajax example (1)

<?phprequire_once ("../xajax.inc.php");

$xajax = new xajax("multiply.server.php");$xajax->registerFunction("multiply");?>

<?phpfunction multiply($x, $y){

$objResponse = new xajaxResponse();$objResponse->addAssign("z", "value", $x*$y);return $objResponse;

}

require("multiply.common.php");$xajax->processRequests();?> multiply.server.php

multiply.common.php

Page 5: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 5

25

xajax example (2)

<?php require("multiply.common.php");?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi tional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona l.dtd"><html>

<head><title>xajax Multiplier</title> <?php $xajax->printJavascript('../'); ?>

</head> <body>

<input type="text" name="x" id="x" value="2" size=" 3" /> * <input type="text" name="y" id="y" value="3" size=" 3" /> = <input type="text" name="z" id="z" value="" size="3 " /> <input type="button" value="Calculate“

onclick="xajax_multiply(document.getElementById('x' ).value,document.getElementById('y').value);return false;" />

</body></html> multiply.php

26

JSON

• JavaScript Object Notation

• A text-based, human-readable format for representing objects and other data structures

• Mainly used to transmit such structured data over a network connection, notably in the context of AJAX

• As an alternative to XML, preformatted HTML or plain text

• A Subset of JavaScript's object literal notation

• Security may be an issue

27

JSON example

{"firstName": "John","lastName": "Smith","address": {

"city": "New York, NY","zipCode": 10021,"streetAddress": "21 2nd Street"

},"phoneNumbers": [

"212 732-1234","646 123-4567"

]}

var p = eval("(" + JSON_text + ")");

28

Using JSON for AJAX

var the_object;var http_request = new XMLHttpRequest();http_request.open("GET", url, true);http_request.onreadystatechange = function () {

if (http_request.readyState == 4) {if (http_request.status == 200) {

the_object = eval("(" + http_request.responseText + ")");

} else {alert("There was a problem with the URL.");

}http_request = null;

}};http_request.send(null);

29

Where we are now

• We've seen several common internet programming technologies

• CGI, JavaScript, CSS, DOM, PHP, Java Servlets, Perl, XML, XSLT, AJAX, …

• We've mostly taken a quite basic "feet in the mud" approach to these technologies

• Build up your application from scratch

• Use little or none external add-ons

• Many other technologies exist and evolve

• Let's have a look at yet another popular one30

Programming webapplications

• Programming webapplications is a lot of work!

• Reinventing the wheel again and again

• Handling form data, input validation, database

access, session management, security and

authentication, …

• Basically, it's all about accessing your data

• View, insert, update, delete through a nice interface

• Could we abstract from most of the "boring" issues?

• Use a framework!

• Evolution is often geared towards this aspect

Page 6: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 6

31

Webapplication frameworks

• A set of software tools to facilitate fast and easy web application development

• Typically provide functionality such as

• Database access

• Templating

• Session management

• Security (authentication, input validation)

• Range from simple libraries to presentationmechanisms to complete systems using the Model-View-Controller concept (MVC)

32

Examples of frameworks

• DBI (Library, Perl based)

• PEAR (Library, PHP based)

• Smarty (Presentation, PHP based)

• ZK (Presentation, Java/AJAX based)

• Django (MVC, Python based)

• Ruby on Rails (MVC, Ruby based)

• CakePHP (MVC, Ruby based)

• Codeigniter (MVC, PHP based)

• WebObjects (Apple proprietary, Java based)

• …

33

Model-View-Controller (1)

• Software architecture

• Separates application's

• Data model

• User interface

• Control logic

• Modification to one

component are possible

with minimal impact on

other components34

Model-View-Controller (2)

• Model

• The domain-specific representation of the information on which the application operates

• View

• Renders the model into a form suitable for interaction, typically a user interface element (HTML for example)

• Controller

• Responds to events, typically user actions, and invokes changes on the model and perhaps the view

35

Model-View-Controller (3)

• Many applications use a persistent storage

mechanism (such as a database) to store data

• In MVC it is understood to be underneath or

encapsulated by the Model

• In web context

(basic interpretation)

• Database / db access layer

• Template / HTML

• Script36

Model-View-Controller (4)

1. The user interacts with the user interface in some way

(e.g., user presses a button)

2. A controller handles the input event from the user

interface, often via a registered handler or callback

3. The controller accesses the model, possibly updating it in a

way appropriate to the user's action (e.g., controller

updates user's shopping cart)

4. A view uses the model to generate an appropriate user

interface (e.g., view produces a screen listing the shopping

cart contents); the view gets its own data from the model

5. The user interface waits for further user interactions, which

begins the cycle anew

Page 7: INP AJAX, JSON, frameworks 1

INP

AJAX, JSON, frameworks 7

37

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


Recommended