51
Zend Framework 5. Ajax, JSON & jQuery Tricode Professional Services www.tricode.nl Date: 20-03-2009 Author: Marcel Blok

Zend framework 05 - ajax, json and j query

  • Upload
    tricode

  • View
    2.096

  • Download
    2

Embed Size (px)

DESCRIPTION

Ajax, JSON & jQuery "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.” – json.org JSON is often used in Ajax calls instead of XML because it’s more lightweight compared to XML, less text is needed for defining the same data.

Citation preview

Page 1: Zend framework 05 - ajax, json and j query

Zend Framework

5. Ajax, JSON & jQuery

Tricode Professional Serviceswww.tricode.nl

Date: 20-03-2009Author: Marcel Blok

Page 2: Zend framework 05 - ajax, json and j query

2

JSONP

“script tag method for cross-domain data fetching: JSON with Padding, or simply JSONP“

– Bob Ippolito (bob.pythonmac.org)

Page 3: Zend framework 05 - ajax, json and j query

3

JSON

“JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.”

– json.org

JSON is often used in Ajax calls instead of XML because it’s more lightweight compared to XML, less text is needed for defining the same data.

Page 4: Zend framework 05 - ajax, json and j query

4

JSON

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

"streetAddress“: "21 2nd Street“, "city“ : "New York“, "state“ : "NY“, "postalCode“ : 10021

}, "phoneNumbers“ : [

"212 555-1234“, "646 555-4567“

]}

object{}{ members }

memberspairpair , members

pairstring : value

array[ ][ elements ]

elementsvalue value , elements

valuestringnumberobjectarraytruefalsenull

Page 5: Zend framework 05 - ajax, json and j query

5

JSONP

callback1237385981851 ({"firstName“ : "John“, "lastName“ : "Smith“, "address“ : {

"streetAddress“ : "21 2nd Street“

, "city“ : "New York“, "state“ : "NY“, "postalCode“ : 10021

}, "phoneNumbers“ : [

"212 555-1234“, "646 555-4567“

]})

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

"streetAddress“ : "21 2nd Street“

, "city“ : "New York“, "state“ : "NY“, "postalCode“ : 10021

}, "phoneNumbers“ : [

"212 555-1234“, "646 555-4567“

]}

JSON

Page 6: Zend framework 05 - ajax, json and j query

6

- Cross-domain- Need server-side

cooperation

JSONP JSON

- Single-domain(even sub-domain!)

- No server-side cooperation needed

Page 7: Zend framework 05 - ajax, json and j query

7

ContextSwitch / AjaxContext

“Zend Framework includes several action helpers by default: … ContextSwitch and AjaxContext for serving alternate response formats for your actions; …”

– ZF Programmer's Reference Guide

The ContextSwitch and AjaxContext controller action helpers are available since Zend Framework version 1.6.

Page 8: Zend framework 05 - ajax, json and j query

8

ContextSwitch / AjaxContext

Setting up the contexts:class NewsController extends Zend_Controller_Action{ public function init() { $contextSwitch = $this->_helper->getHelper('contextSwitch'); $contextSwitch->addActionContext('list', 'xml') ->addActionContext('listarchive', array( 'xml' , 'json' )) ->initContext(); }

// ...}

Page 9: Zend framework 05 - ajax, json and j query

9

ContextSwitch / AjaxContext

The action:class NewsController extends Zend_Controller_Action{

public function listAction() { $nm = new News_Mapper(); $news = $nm->fetchAll(); $this->view->news = $news; } // ...}

Page 10: Zend framework 05 - ajax, json and j query

10

ContextSwitch / AjaxContext

The view (news/list.xml.phtml):

<?xml version="1.0" encoding="UTF-8"?><?php foreach ($this->news as $msg): /* @var $msg News */ ?><news> <id><?php echo $msg->getId(); ?></id> <title><?php echo $msg->getTitle(); ?></title> <summary><?php echo $msg->getSummary(); ?></summary></news><?php endforeach; ?>

Page 11: Zend framework 05 - ajax, json and j query

11

ContextSwitch / AjaxContext

• ContextSwitch provides the following response formats by default:– ‘json’, no view is needed when using this format– ‘xml’, an action view with the suffix ‘.xml.phtml’ is needed

for this format

• AjaxContext extends the ContextSwitch with the following format:– ‘html’, an action view with the suffix ‘.ajax.phtml’ is needed

for this format

Note: when a context action is not called thru a XHR request, the action will render it’s normal view with the ‘.phtml’ suffix.

Page 12: Zend framework 05 - ajax, json and j query

12

JsonResponse vs ContextSwitch

• Works on ALL controller actions without extra work

• Can only respond JSONP format

• No special views are needed

• Needs to be configured for each controller action that wants to provide other response formats

• Can response xml and JSON by default. AjaxContext extends this with html. Other contexts can be added

• Depending on the format a special view is needed

Page 13: Zend framework 05 - ajax, json and j query

13

jQuery

The write less, do more JavaScript library

“jQuery is a fast and concise JavaScript Library that

simplifies HTML document traversing, eventhandling, animating, and Ajax interactions for

rapidweb development. jQuery is designed to changethe way that you write JavaScript.”

Page 14: Zend framework 05 - ajax, json and j query

14

Why jQuery?

All major JavaScript frameworks have pros and cons

Then why favor jQuery over the others?

• Large and active community• Very small footprint• Easy to learn• Design-centric

Page 15: Zend framework 05 - ajax, json and j query

15

Browser compatibility

All native functionality is cross-browser compliant:

• Internet Explorer 6.0 +• Firefox 2 +• Safari 3.0+• Opera 9.0+• Chrome

Page 16: Zend framework 05 - ajax, json and j query

16

jQuery namespace

Always remember:Global variables are evil!

• jQuery introduces one symbol to the global namespace: ‘jQuery’

• A shortcut is also added: ‘$’• All jQuery functionality is available from this

symbol.

Page 17: Zend framework 05 - ajax, json and j query

17

jQuery namespace conflicts

Since other frameworks may also use the ‘$’variable, it is possible to revert the inclusion of it:

jQuery.noConflict();

You may use it though like so:

(function($) {

// Within this block, $ is a reference to jQuery

$.doSomething();

})(jQuery);

Page 18: Zend framework 05 - ajax, json and j query

18

JavaScript enhancements

• JQuery adds some functionality that is lacking in JavaScript: each, grep, map, merge, trim, etc.

• All enhancements are available only from the jQuery namespace:

var myArray = [“a”, “b”, “f”, “a”, “d”];alert($.isArray(myArray));

Page 19: Zend framework 05 - ajax, json and j query

19

JavaScript enhancements

Browser and Feature Detection:

• jQuery.support()

Test operations:

• jQuery.isArray(object)• jQuery.isFunction(object)

Page 20: Zend framework 05 - ajax, json and j query

20

JavaScript enhancements

Array and Object operations:

• jQuery.each(object, callback)• jQuery.extend(target, object1, objectN)• jQuery.grep(array, callback, invert)• jQuery.makeArray(object)• jQuery.map(array, callback)• jQuery.inArray(value, array)• jQuery.merge(array1, array2)• jQuery.unique(array)

Page 21: Zend framework 05 - ajax, json and j query

21

JavaScript enhancements

String operations:

• jQuery.trim(string)

URLs:

• jQuery.param(object)

Page 22: Zend framework 05 - ajax, json and j query

22

Selectors

Since jQuery is quite design-orientated and uses theDOM model centrally, the usual starting point of any jQuery statement is selecting one or more nodes to start the operation on.

jQuery has it’s own ‘language’ to select the nodes,combining:

• CSS 1, 2 & 3• Custom expressions

Page 23: Zend framework 05 - ajax, json and j query

23

Selectors

To clarify this odd combination of Xpath and CSSselectors here are some examples:

// Hide all Paragraph elements that contain a class attribute$("p[class]").hide();

// Show the first paragraph on the page$("p:eq(0)").show();

// Hide all divs that are currently showing$("div:visible").hide();

// Get all list items that are children of an unordered list$("ul/li"); // or$("ul > li");

Page 24: Zend framework 05 - ajax, json and j query

24

Selectors

More examples:

// Get all Paragraphs, with class 'foo', that contain a link

$("p.foo[a]");

// Get list item that contains link with "Register" text inside

$("li[a:contains('Register')]");

// Get the input field's value with the name of 'bar'

$("input[@name=bar]").val();

// All checked radio buttons

$("input[@type=radio][@checked]");

Page 25: Zend framework 05 - ajax, json and j query

25

CSS Selectors

* any element E an element of type E E:nth-child(n) an E element, the n-th child of its parent E:first-child an E element, first child of its parent E:last-child an E element, last child of its parent E:only-child an E element, only child of its parent E:empty an E element that has no children (including text

nodes) E:enabled a user interface element E which is not disabled E:disabled a user interface element E which is disabled E:checked a user interface element E which is checked E:selected a user interface element E which is selected E.warning an E element whose class is "warning" E#myid an E element with ID equal to "myid" (matches 1

element) E:not(s) an E element that does not match simple selector s E F an F element descendant of an E element E > F an F element child of an E element E + F an F element immediately preceded by an E element E ~ F an F element preceded by an E element E,F,G select all E elements, F elements, and G elements

Page 26: Zend framework 05 - ajax, json and j query

26

CSS attribute selectors

All available attribute selectors:

E[foo] an E element with a "foo" attribute E[foo=bar] E with "foo" attribute value exactly equal to

"bar" E[foo!=bar] E with "foo" attribute value not equal to "bar" E[foo^=bar] E with "foo" attribute value begins with "bar" E[foo$=bar] E with "foo" attribute value ends with "bar" E[foo*=bar] E with "foo" attribute value contains

substring "bar" E[foo=bar][baz=bop] E with "foo" attribute value exactly equal to

"bar" and with "baz" attribute exactly equal to "bop"

Page 27: Zend framework 05 - ajax, json and j query

27

Custom selectors

All available attribute selectors:

:even Every other (even) element from the matched element set

:odd Every other (odd) element from the matched element set

:eq(N) or :nth(N) The Nth element from the matched element set :gt(N) All matched elements whose index is greater than N:lt(N) All matched elements whose index is less than N:first Equivalent to :eq(0) :last The last matched element:parent All elements which have child elements (including

text):contains('test') All elements which contain the specified text:visible All visible elements:hidden All hidden elements

Page 28: Zend framework 05 - ajax, json and j query

28

Form selectors

All available attribute selectors:

:input All form elements (input, select, textarea, button):text All text fields (type="text"):password All password fields (type="password"):radio All radio fields (type="radio"):checkbox All checkbox fields (type="checkbox"):submit All submit buttons (type="submit"):image All form images (type="image"):reset All reset buttons (type="reset"):button All other buttons (type="button"):file All <input type="file">

Page 29: Zend framework 05 - ajax, json and j query

29

Selector context

Normally the context of the selector will be theentire HTML document.

But you specify a certain context:

var myForm = document.getElementById(‘myForm’);

$('input:radio', myForm);

var myForm = $(‘#myForm’);

$('input:radio', myForm);

Page 30: Zend framework 05 - ajax, json and j query

30

What’s next?

So you are able to easily select every node of theDOM.

What can you do with it?

Page 31: Zend framework 05 - ajax, json and j query

31

Actions

• Further filtering and finding• Manipulate attributes or content (text or HTML)• Adding, removing, prepending, appending,

wrapping, cloning or replacing content• Manipulating CSS• Event binding or triggering• Animating• Get content through AJAX

Page 32: Zend framework 05 - ajax, json and j query

32

Filtering and finding

Filtering and finding can be done to change thecurrent selection of elements.

Some examples:

// Selects all paragraphs and removes those without a class

// "selected".

$("p").filter(".selected")

// Selects all paragraphs, then slices the selection to include

// only the first and second element.

$("p").slice(0, 2)

Page 33: Zend framework 05 - ajax, json and j query

33

Filtering and finding

More examples:

// Find all children with a class "selected" of each div.

$("div").children(".selected")

// Find the parent element of each paragraph with a class

// "selected".

$("p").parent(".selected")

// Locate all elements in front of the last div

$("div:last").prevAll()

Page 34: Zend framework 05 - ajax, json and j query

34

Manipulate attributes and content

One common task that has to be done is to makechanges to the attributes of selected DOMelements:

// Disables buttons greater than the 1st button.

$("button:gt(1)").attr("disabled", "disabled");

// Remove the style attribute from all elements

$("*").removeAttr("style");

// Toggle the class 'highlight' of all paragraphs

$("p").toggleClass("highlight");

Page 35: Zend framework 05 - ajax, json and j query

35

Manipulate attributes and content

More examples:

// Add some html to each div

$("div").html("<span class='red'>Hello <b>Again</b></span>");

// Get the text from the first paragraph

var str = $("p:first").text();

// Set the value of a multiple select box

$("#multiple").val(["Multiple2", "Multiple3"]);

Page 36: Zend framework 05 - ajax, json and j query

36

Changing content

Another common thing to do is changing thecontent in or around the selection:

// Appends an Element inside all paragraphs.

$("p").append(document.createTextNode("Hello"));

// Wrap a jQuery object around all of the paragraphs. Notice it

// doesn't move the object but just clones it to wrap around

// its target.

$("p").wrap($(".doublediv"));

// Removes all paragraphs that contain "Hello" from the DOM

$("p").remove(":contains('Hello')");

Page 37: Zend framework 05 - ajax, json and j query

37

Manipulating CSS

Maybe the most common action you need to takeis make changes to the styling of the selectedelement:

// To change the color of any paragraph to

$("p").css("color", "red");

// Scroll the demo div 300 to the left

$("div.demo").scrollLeft(300);

// Get the inner width of the first paragraph

var myWidth = $("p:first").innerWidth();

Page 38: Zend framework 05 - ajax, json and j query

38

Event binding and triggering

Often you need to react on actions that a usertakes. In order to accomplish this you need to

bindfunctions to elements that will be triggered by theaction of the user or the system:

// Run code when the DOM loads

$(document).ready(function(){

// Your code here...

});

// Show a paragraph's text in an alert box when it is clicked

$("p").bind("click", function(){

alert( $(this).text() );

});

Page 39: Zend framework 05 - ajax, json and j query

39

Event binding and triggering

More examples:

// Trigger the click event on each paragraph$("p").trigger("click"); // or$("p").click();

// Trigger functions upon hovering of a paragraph$("p").hover(

function(){ $(this).addClass("over");

},function(){

$(this).addClass("out"); }

);

Page 40: Zend framework 05 - ajax, json and j query

40

Animating

Sometimes you may need to add some commonanimation to an element:

// Hide all paragraphs

$("p").hide();

// Slowly show all paragraphs, then alert that it’s done

$("p").show("slow", function(){

alert("Animation Done.");

});

// Fade all paragraphs to 50% opactity within 1000ms

$("p").fadeTo(1000, 0.5);

Page 41: Zend framework 05 - ajax, json and j query

41

Animating

Custom animation can also be accomplished byproviding the style elements that need to beadapted:

// Animate the position and opacity in 0.5 seconds

$("p").animate({ left: 50, opacity: 'show' }, 500);

// An example of using an 'easing' function to provide a

// different style of animation. This will only work if

// you have a plugin that provides this easing function

$("p").animate({ opacity: 'show' }, "slow", "easein");

Page 42: Zend framework 05 - ajax, json and j query

42

AJAX

Finally, one of the most flexible things you can dowith jQuery is perform AJAX requests or respond

toglobal AJAX events.

Page 43: Zend framework 05 - ajax, json and j query

43

Global AJAX events

Global AJAX events are broadcast to all elements inthe DOM, and trigger any handlers that arelistening. These events are:

ajaxCompleteajaxErrorajaxSendajaxStartajaxStopajaxSucces

Page 44: Zend framework 05 - ajax, json and j query

44

Global AJAX events

An example of how to use this:

// Show the loading box during all AJAX requests

$("#loading").bind("ajaxSend", function(){

$(this).show();

}).bind("ajaxComplete", function(){

$(this).hide();

});

Please note that a specific AJAX request mayspecify not to trigger the global events.

Page 45: Zend framework 05 - ajax, json and j query

45

AJAX requests

Often an AJAX request may be as simple asfetching HTML into an element:

$('#stats').load('stats.html');

Or sending data to the server:

$.post('save.cgi', {

text: 'my string',

number: 23

}, function() {

alert('Your data has been saved.');

});

Page 46: Zend framework 05 - ajax, json and j query

46

Complex AJAX requests

Sometimes you may need to do more complex stuff with or during the AJAX request. You can tweakevery detail of the request:

$.ajax({

url: 'document.xml',

type: 'GET',

dataType: 'xml',

timeout: 1000,

error: function(){

alert('Error loading XML document');

},

success: function(xml){

// do something with xml

}

});

Page 47: Zend framework 05 - ajax, json and j query

47

Ajax Event stack

ajaxStart (global) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.

beforeSend (local) Triggered before an Ajax request is started

ajaxSend (global) Triggered before the request is run. success (local) Called if request was successfulajaxSuccess (global) Same, but globalerror (local) Called if an error occurredajaxError (global) Same, but globalcomplete (local) Called regardless of if the

request was successful, or not. ajaxComplete (glob.) Same, but global ajaxStop (global) This global event is triggered if there

are no more Ajax requests being

processed.

Page 48: Zend framework 05 - ajax, json and j query

48

XML AJAX requests

Please note that jQuery also operates on XMLdocuments, not only HTML documents!

success: function(xml){

// Find each 'item'

$(xml).find('item').each(function(){

var item_text = $(this).text();

// Append the item text as a list item to <ol>

$('<li></li>')

.html(item_text)

.appendTo('ol');

});

}

Page 49: Zend framework 05 - ajax, json and j query

49

JSON AJAX requests

Of course it is also possible to use JSON in therequests as in the following example:

$.getJSON("/select.php",{id: someval}, function(j){

var options = '';for (var i = 0; i < j.length; i++) {

options += '<option value="' + j[i].optionValue +

'">' + j[i].optionDisplay + '</option>';}$("select#ctlPerson").html(options);

})

Page 50: Zend framework 05 - ajax, json and j query

50

JSONP AJAX requests

JSONP calls are also possible. jQuery willautomatically generate a callback function for you.You only need to specify the “callback=?”(depending on API) parameter in your request:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",

function(data){

$.each(data.items, function(i,item){ $("<img/>").attr("src",item.media.m).appendTo("#imgs");

if ( i == 3 ) return false;

});

});

Page 51: Zend framework 05 - ajax, json and j query

51

Tasks

• Continue your own application• Make some layout-enhancements using jQuery:

– Tables have a different color on odd and even rows– Links and buttons get another style/color upon

hovering– Think of your own!

• Rewrite the application to use some Ajax validations using jQuery

• Use jQuery to show/hide errormessages on a field