jQueryAjax

advertisement
jQuery – Ajax
• jQuery includes support for Ajax
• Greatly simplifies code
• Browser independent (you still
need to test on all browsers)
jQuery - Ajax
• See documentation at
jquery.com
• Most powerful function is
probably load: makes ajax call
and loads result in some HTML
element, can also call a
callback function
jQuery – Ajax .load()
Loads data from the server and
places the result into the
matched elements (directly)
Data from the server can be as
simple as file contents
$( “#id3” ).load( “data.txt” );
jQuery – Ajax .load()
Or it can call a script, pass
parameters to it, even setup a
callback function to be called
after the ajax call is completed
$( “#id4” ).load( “test.php”, {
name: “Mike”, age: 21 }, callMe );
jQuery – Ajax .load()
The data is sent to the server
using the POST method
In php, retrieved using $_POST[
‘name’] or $_POST [‘age’]
jQuery – Ajax .load()
After the Ajax call is completed
the callback function executes
(here callMe)
The callback function has access
to 3 parameters: responseText,
textStatus, XMLHttpRequest
jQuery – Ajax .load()
• responseText  what is
output/returned by the server
• textStatus  success or error
• XMLHttpRequest  The
XMLHttpRequest object
We are mostly interested in
responseText .. which is already
loaded in the element(s)
jQuery – ajax
Another method, this one call by
jQuery (or $) is ajax
The syntax is:
jQuery.ajax( url [, settings] )
Where settings is a set of
key/value pairs in object
notation
jQuery – ajax
Some of the keys for settings:
type  GET (default) or POST
data  string in query string form
if using POST (if using GET 
append query string to url)
success  callback function
jQuery – ajax
$.ajax( "test.php?user=Bob&age=17",
{success: callMe3} );
Default method is GET
 retrieve Bob and 17 via $_GET[‘user’]
and $_GET[‘age’] on server side
(inside test.php)
Function callMe3 is the callback
function
jQuery – ajax
$.ajax( "script.php", {data:
"user=Sarah&age=19", type: "POST",
success: callMe3} );
method is POST
 retrieve Sarah and 19 via
$_POST[‘user’] and $_POST[‘age’] on
server side (inside script.php)
Function callMe3 is the callback
function
jQuery – ajax
After the Ajax call is completed
the callback function executes
(here callMe3)
As before, the callback function
has access to 3 parameters:
responseText, textStatus,
XMLHttpRequest
Download