Download presentation
Presentation is loading. Please wait.
Published byTyrone Cole Modified over 10 years ago
1
jQuery Ajax, Command Chaining, and Closure
2
Review You can attach events to items using click or mouseover or mouseout –$(‘button‘).click(function(){alert('You clicked')}) You can retrieve and change the contents of an html element using the html function: –var x = $(‘#xyz’).html(); –$(‘#lue’).html(“Forty Two”); For control elements – such as the text box and textarea use val to get and put values
3
Ajax – Sending data You can make calls to the server from your web browser using $.ajax You can provide data in a hash list: $('#add').click(function(){ $.ajax({url:'adduser.php', data:{who:$('#myname').val() } });
4
Ajax mechanics The browser will send the key/value pairs to the server. In the above example there is no response worth reading. The script at the server can process the data: <?php $fh = fopen('users.txt','a'); fwrite($fh,"$_REQUEST[who]\n"); ?> adduser.php
5
Three components....html.js.php Add your name to the list: Add Everyone: Show
6
Firebug Console Firebug will show the data going from the browser to the server. Each exchange has Params and HTML.
7
Getting a result The ajax call now has a success function associated. This function will run when the browser receives a response. The call is asynchronous. $('#show').click(function(){ $.ajax({url:'users.txt',success:function(d){ $('#everyone').val(d); }})});
8
Chaining Commands Most functions to change an element return the element and so we can chain commands var d = $(' ').html('Andrew was here').css('color','red'); $('body').append(d);
9
Avoid names You can use the appendTo function – this allows you to put the append at the end of the chain: $(' ').html('Andrew was here').css('color','red').appendTo($('body'));
10
You can create nested elements Often you need to create elements that contain other elements It should be clear –Where css is applied –What gets appended $(' ').html('Outer div').css('color','red').append( $(' ').css('font-weight','bold').html('Inner div')).appendTo($('body'));
11
end() chaining You may need to traverse the tree, change something, then change the original context. $('ul').find('li:first-child').css('color','red').end().css('border','solid'); Without.end() With.end()
12
Closure When a function is declared in line it picks up the local variables. This context may be shared... for (var i=0;i<4;i++) $('body').append($(' ',{text:i}).click(function(){ alert(i); }));
13
Closure In the code above the variable i is shared by every function. The each of the functions operates in the same context. In some cases you need each variable to have its own copy of the variable. You can create a new closure You can save data against an element
14
Fixing the problem – with closure You need to create a new closure if you create a function: for (var i=0;i<4;i++){ var f=function(j){ $('body').append($(' ', {text:i, click:function()(alert(j))})); }; f(i); }
15
Fixing the problem with data You can store data against an element $('#abc').data('key', 123); for (var i=0;i<4;i++){ $('body').append($(' ', {text:i, data:{x:i}, click:function()(alert($(this).data('x'))) })); }
16
Integrating with CMS In a typical content management system you can create extensions or modules These allow you to insert PHP generated elements into your page ==Libya== <question title='Libya' imgOut='flag.png' width='150' height='100' className="Raster" rows='10' level='1'> The flag of Libya is a simple green rectangle. Try the program as it is given, then change it so that the green rectangle is 150 wide. [[Image:flaglibya.png|border]] static void drawFlag(Graphics g) { g.setColor(new Color(0,128,0)); g.fillRect(0,0,150,100); } ==Libya== <question title='Libya' imgOut='flag.png' width='150' height='100' className="Raster" rows='10' level='1'> The flag of Libya is a simple green rectangle. Try the program as it is given, then change it so that the green rectangle is 150 wide. [[Image:flaglibya.png|border]] static void drawFlag(Graphics g) { g.setColor(new Color(0,128,0)); g.fillRect(0,0,150,100); }
17
Generate HTML from the Server In MediaWiki you can create an extension that will interpret custom XML elements. In the ProgZoo example the custom XML element is processed by a PHP function that outputs an HTML element The generated HTML has the functionality required – something beyond what the MediaWiki will do Other CMS systems allow similar modules/extensions /templates function question( $input, $argv, $parser ) { global $errMsg; global $wgCurRevisionId;... function question( $input, $argv, $parser ) { global $errMsg; global $wgCurRevisionId;...
18
Advantages of Server-side generation The code can be written in any server-side language: Java, PHP, C# You do not have to disclose all of the parameters in the HTML In the progzoo example – we do not have to embed the answer to the questions in the HTML The page can be rendered instantly – the user does not have to wait for the JavaScript “onready” function to complete.
19
Do it in jQuery You can have jQuery generate your custom elements Here the tag is produced at the browser jQuery find the tag and “zooifies” it after it has loaded.
20
Advantages of jQuery customisation All the functionality resides only in the JavaScript file You can have “graceful degredation” if you do it well –Some data will be visible, some will be invisible You do not have to “fight” the CMS Development time is typically much faster Essentially you can have... –User interface work done in JavaScript (you can’t avoid that anyway) –Generation of data at the server in the simplest format possible The data generate by the server can be: –Delivered as JSON after page load –Embedded hidden in the HTML (not securely hidden – just invisible to the casual user) –Embedded visibly in the HTML in as simple a format as possible
21
How far to take the JavaScript Inevitably you have to have some functionality in HTML and some in JavaScript The rich client does not sit entirely comfortably with the MVC pattern You want to avoid having a representation of the same object being echoed at the client and the server A typical interaction might be: –Client requests a complex object – a “document” –Client makes changes to the document and sends updates to the server –At each small change the client receives pretty much the whole document back again –The client rebuilds the representation – this is less drastic than a page refresh but still tricky to show transitions easily.
22
Embedding data in HTML You can keep the “document” in it’s internal representation as a data object in jQuery – this is usually attached to the body node The source of the data could be an onload ajax call or it could be in a hidden field in the HTML $(function(){ $('body').data('doc',$.parseJSON($('#embeddedData').val())); }); $(function(){ $('body').data('doc',$.parseJSON($('#embeddedData').val())); }); $(function(){ $.getJSON("data.cgi",function(d){ $('body').data('doc',d); }); $(function(){ $.getJSON("data.cgi",function(d){ $('body').data('doc',d); });
23
Retrieving data You can query the body data objects swiftly In this example the doc object has three fields: –bcf – balance carried forward –odl – overdraft limit –trn – transactions. A list of objects with three fields: whn – the date in ISO format “2013-12-25” nar – a description, “DIRECT DEBIT - EDINBURGH COUNCIL” amt – an integer, positive for income, negative for spending $('#bcf').text( $('body').data('doc').bcf );
24
What have we missed? We have covered many of jQuery’s functions but we have missed: –jQuery UI – there are many third party additions to jQuery including special controls and special effects: date pickers, auto-complete and many many others –Ajax – there are many different ways to exploit Ajax. We have only scratched the surface. –JSON – we can export and import complex data structures as JSON strings. These are fast and flexible.
25
Summary jQuery is a library that makes JavaScript coding fast and relatively easy. jQuery runs in the browser, it can be used to make pages change without a trip to the server. We can build rich interactive environments. It is ironic that an open source, un-managed code base comes along to save a certified, documented standard such as ECMA-Script
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.