Programming4us
         
 
 
Programming

jQuery 1.3 : AJAX - Passing data to the server

6/11/2011 3:32:04 PM
Our examples to this point have focused on the task of retrieving static data files from the web server. However, the AJAX technique really comes into its own only when the server can dynamically shape the data based on input from the browser. We're helped along by jQuery in this task as well; all of the methods we've covered so far can be modified so that data transfer becomes a two-way street.

Since demonstrating these techniques requires interaction with the web server, we'll need to use server-side code for the first time here. The examples given will use the PHP scripting language, which is very widely used as well as freely available. We will not cover how to set up a web server with PHP here; help on this can be found on the websites of Apache (http://apache.org/) or PHP (http://php.net/), or from your site's hosting company.


Performing a GET request

To illustrate the communication between client and server, we'll write a script that only sends one dictionary entry to the browser on each request. The entry chosen will depend on a parameter sent from the browser. Our script will pull its data from an internal data structure like this:

<?php
client and server communicationGET request, performing$entries = array(
'EAVESDROP' => array(
'part' => 'v.i.',
'definition' => 'Secretly to overhear a catalogue of the
crimes and vices of another or yourself.',
'quote' => array(
'A lady with one of her ears applied',
'To an open keyhole heard, inside,',
'Two female gossips in converse free &mdash;',
'The subject engaging them was she.',
'"I think," said one, "and my husband thinks',
'That she\'s a prying, inquisitive minx!"',
'As soon as no more of it she could hear',
'The lady, indignant, removed her ear.',
'"I will not stay," she said, with a pout,',
'"To hear my character lied about!"',
),
'author' => 'Gopete Sherany',
),
'EDIBLE' => array(
'part' => 'adj.',
'definition' => 'Good to eat, and wholesome to digest, as
a worm to a toad, a toad to a snake, a snake to a pig,
a pig to a man, and a man to a worm.',
),
'EDUCATION' => array(
'part' => 'n.',
'definition' => 'That which discloses to the wise and
disguises from the foolish their lack of
understanding.',
),
);
?>


In a production version of this example, the data would probably be stored in a database and loaded on demand. Since the data is a part of the script here, the code to retrieve it is quite straightforward. We examine the data that has been posted and craft the HTML snippet to display:
<?php
$term = strtoupper($_REQUEST['term']);
if (isset($entries[$term])) {
$entry = $entries[$term];
$html = '<div class="entry">';
$html .= '<h3 class="term">';
$html .= $term;
$html .= '</h3>';
$html .= '<div class="part">';
$html .= $entry['part'];
$html .= '</div>';
$html .= '<div class="definition">';
$html .= $entry['definition'];
if (isset($entry['quote'])) {
client and server communicationGET request, performing$html .= '<div class="quote">';
foreach ($entry['quote'] as $line) {
$html .= '<div class="quote-line">'. $line .'</div>';
}
if (isset($entry['author'])) {
$html .= '<div class="quote-author">'. $entry['author']
.'</div>';
}
$html .= '</div>';
}
$html .= '</div>';
$html .= '</div>';
print($html);
}
?>



Now requests to this script, which we'll call e.php, will return the HTML snippet corresponding to the term that was sent in the GET parameters. For example, when accessing the script with e.php?term=eavesdrop, we get back:

Once again, we note the lack of formatting we saw with earlier HTML snippets, because CSS rules have not been applied.

Since we're showing how data is passed to the server, we will use a different method to request entries than the solitary buttons we've been relying on so far. Instead, we'll present a list of links for each term, and cause a click on any of them to load the corresponding definition. The HTML we'll add for this looks like:

<div class="letter" id="letter-e">
<h3>E</h3>
<ul>
<li><a href="e.php?term=Eavesdrop">Eavesdrop</a></li>
<li><a href="e.php?term=Edible">Edible</a></li>
<li><a href="e.php?term=Education">Education</a></li>
<li><a href="e.php?term=Eloquence">Eloquence</a></li>
<li><a href="e.php?term=Elysium">Elysium</a></li>
<li><a href="e.php?term=Emancipation">Emancipation</a>
</li>
<li><a href="e.php?term=Emotion">Emotion</a></li>
<li><a href="e.php?term=Envelope">Envelope</a></li>
<li><a href="e.php?term=Envy">Envy</a></li>
<li><a href="e.php?term=Epitaph">Epitaph</a></li>
<li><a href="e.php?term=Evangelist">Evangelist</a></li>
</ul>
</div>

Now we need to get our JavaScript code to call the PHP script with the right parameters. We could do this with the normal .load() mechanism, appending the query string right to the URL and fetching data with addresses like e.php?term=eavesdrop directly. Instead, though, we can have jQuery construct the query string based on a map we provide to the $.get() function:

$(document).ready(function() {
$('#letter-e a').click(function() {
$.get('e.php', {'term': $(this).text()}, function(data) {
$('#dictionary').html(data);
});
return false;
});
});

Now that we have seen other AJAX interfaces that jQuery provides, the operation of this function seems familiar. The only difference is the second parameter, which allows us to supply a map of keys and values that become part of the query string. In this case, the key is always term but the value is taken from the text of each link. Now, clicking on the first link in the list causes its definition to appear:

All the links here have addresses given, even though we are not using them in the code. This provides an alternative method of navigating the information for users who have JavaScript turned off or unavailable (a form of progressive enhancement). To prevent the links from being followed normally when clicked, the event handler has to return false.

Performing a POST request

HTTP requests using the POST method are almost identical to those using GET. One of the most visible differences is that GET places its arguments in the query string portion of the URL, whereas POST requests do not. However, in AJAX calls, even this distinction is invisible to the average user. Generally, the only reason to choose one method over the other is to conform to the norms of the server-side code, or to provide for large amounts of transmitted data; GET has a more stringent limit. We have coded our PHP example to cope equally well with either method, so we can change from GET to POST simply by changing the jQuery function we call:

$(document).ready(function() {
$('#letter-e a').click(function() {
$.post('e.php', {'term': $(this).text()}, function(data) {
$('#dictionary').html(data);
});
return false;
});
});

The arguments are the same, and the request will now be made via POST. We can further simplify the code by using the .load() method, which uses POST by default when it is supplied with a map of arguments:

$(document).ready(function() {
$('#letter-e a').click(function() {
$('#dictionary').load('e.php', {'term': $(this).text()});
return false;
});
});

This cut-down version functions the same way when a link is clicked:

Serializing a form

Sending data to the server often involves the user filling out forms. Rather than relying on the normal form submission mechanism, which will load the response in the entire browser window, we can use jQuery's AJAX toolkit to submit the form asynchronously and place the response inside the current page.

To try this out, we'll need to construct a simple form:

<div class="letter" id="letter-f">
<h3>F</h3>
<form>
<input type="text" name="term" value="" id="term" />
<input type="submit" name="search" value="search"
id="search" />
</form>
</div>

This time we'll return a set of entries from the PHP script by searching for the supplied search term as a substring of a dictionary term. The data structure will be of the same format as before, but the logic will be a bit different:

foreach ($entries as $term => $entry) {
if (strpos($term, strtoupper($_REQUEST['term']))
!== FALSE) {
$html = '<div class="entry">';
$html .= '<h3 class="term">';
$html .= $term;
$html .= '</h3>';
$html .= '<div class="part">';
$html .= $entry['part'];
$html .= '</div>';
$html .= '<div class="definition">';
$html .= $entry['definition'];
if (isset($entry['quote'])) {
foreach ($entry['quote'] as $line) {
$html .= '<div class="quote-line">'. $line .'</div>';
}
if (isset($entry['author'])) {
$html .= '<div class="quote-author">'.
$entry['author'] .'</div>';
}
}
$html .= '</div>';
$html .= '</div>';
print($html);
}
}


The call to strpos() scans the word for the supplied search string. Now we can react to a form submission and craft the proper query parameters by traversing the DOM tree:

$(document).ready(function() {
$('#letter-f form').submit(function() {
$('#dictionary').load('f.php',
{'term': $('input[name="term"]').val()});
return false;
});
});

This code has the intended effect, but searching for input fields by name and appending them to a map one by one is cumbersome. In particular, this approach does not scale well as the form becomes more complex. Fortunately, jQuery offers a shortcut for this often-used idiom. The .serialize() method acts on a jQuery object and translates the matched DOM elements into a query string that can be passed along with an AJAX request. We can generalize our submission handler as follows:

$(document).ready(function() {
client and server communicationform, constructing$('#letter-f form').submit(function() {
$.get('f.php', $(this).serialize(), function(data) {
$('#dictionary').html(data);
});
return false;
});
});


Now the same script will work to submit the form, even as the number of fields increases. When we perform a search, the matched entries are displayed:

Other -----------------
- iPhone Programming : Other View Controllers - Tab Bar Applications
- iPhone Programming : Other View Controllers - Utility Applications
- iPhone Programming : Table-View-Based Applications - Adding a City View
- iPhone Programming : Table-View-Based Applications - Adding Navigation Controls to the Application
- iPad SDK : Popovers - Popover Preparations
- iPad SDK : Preparing Dudel for a New Tool (part 5) - Rendering Multiple Styles
- iPad SDK : Preparing Dudel for a New Tool (part 4) - Creating a New Drawable Class
- jQuery 1.3 : AJAX - Loading data on demand (part 3) - Loading an XML document
- jQuery 1.3 : AJAX - Loading data on demand (part 2) - Working with JavaScript objects
- jQuery 1.3 : AJAX - Loading data on demand (part 1) - Appending HTML
- Coding JavaScript for Mobile Browsers (part 13) - Zoom and rotate gestures
- Coding JavaScript for Mobile Browsers (part 12) - Swipe gesture
- Coding JavaScript for Mobile Browsers (part 11)
- Coding JavaScript for Mobile Browsers (part 10) - Event Handling
- iPad SDK : Preparing Dudel for a New Tool (part 3) - Creating the Text Tool
- iPad SDK : Preparing Dudel for a New Tool (part 2) - Implementing Changes to the Controller Class
- Coding JavaScript for Mobile Browsers (part 9) - Scripting Styles
- Coding JavaScript for Mobile Browsers (part 8) - DOM
- iPad SDK : Preparing Dudel for a New Tool (part 1) - Setting Up the GUI
- Coding JavaScript for Mobile Browsers (part 7)
 
 
Most View
- SharePoint 2010 : Using Windows PowerShell: The Basics
- Setting Up a Full-Text Index (part 2) - Full-Text Indexing of BLOBs and XML
- Active Directory Domain Services 2008: Configure Auditing on Object Security Access Control Lists
- Exchange 2007: How Do I Modify a Database Size Limit?
- An OLAP Requirements Example: CompSales International (part 8) - Aggregating Data Within the Cube
- Exchange Server 2010 : Upgrading from and Coexisting with Exchange Server 2003 (part 3)
- SQL Server 2008: Administering Database Objects - Working with Tables (part 1) - Default Constraints
- Windows Phone 7 : Synching Media with Your Phone
- SharePoint 2010 : Assign Users’ Permissions on a Site
- Administering SQL Server 2008 with PowerShell : Step-By-Step Examples (part 4)
Top 10
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 3) - Configuring Recipient Filtering
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 2)
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Implementing Edge Services for an Exchange Server 2007 Environment : Installing and Configuring the Edge Transport Server Components
- What's New in SharePoint 2013 (part 7) - BCS
- What's New in SharePoint 2013 (part 6) - SEARCH
- What's New in SharePoint 2013 (part 6) - WEB CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 5) - ENTERPRISE CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 4) - WORKFLOWS
- What's New in SharePoint 2013 (part 3) - REMOTE EVENTS