Multiple AJAX responses with 1 request (mootools and PHP)
Why separate requests aren’t great
If you want to update three separate regions, then using separate requests means that you’re waiting longer. 3 times you make a request and 3 times you wait for a response, rather than making 1 request, waiting for 1 response and processing the result. So here is how I’d consolidate everything into the one request:
<div id="container">
<a href="#" title="id=1">Make a request</a> -
<a href="#" title="id=2">Make a different request</a> -
<a href="#" title="id=3">Clear the regions</a>
<br /><br />
<div id="one"></div>
<div id="two"></div>
<br class="clear-both" />
<div id="three"></div>
<br class="clear-both" />
</div>
AJAX – The XMLHttpRequest Object
Before sending data to the server, we have to explain three important properties of the XMLHttpRequest object.
The onreadystatechange Property
After a request to the server, we need a function that can receive the data that is returned by the server.
The onreadystatechange property stores your function that will process the response from a server. This is not a method, the function is stored in the property to be called automatically. The following code sets the onreadystatechange property and stores an empty function inside it:
xmlHttp.onreadystatechange=function()
{
// We are going to write some code here
}
Class AjaxRequest
boolean- aborted
An internal flag to indicate whether the request has been aborted
boolean- async
Whether or not the request will be asynchronous.
boolean- generateUniqueUrl
Since some browsers cache GET requests via XMLHttpRequest, an additional parameter called AjaxRequestUniqueId will be added to the request URI with a unique numeric value appended so that the requested URL will not be cached.
string- groupName
The name of the group that this request belongs to, for activity monitoring purposes
How to use XMLHttpRequest
In this method, you can instantiate an XMLHttpRequest object that can then call functions from the server. The code is in the public domain.
function getNewHTTPObject()
{
var xmlhttp;
/** Special IE only code ... */
/*@cc_on
@if (@_jscript_version >= 5)
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}return xmlhttp;
How To Handle AJAX Responses
User interaction drives Web sites. It’s essential to understand how to handle the responses, especially with new forms of interaction such as AJAX. Kris Hadlock covers the essentials of the AJAX request-and-response process that you need to know to be ready for user interaction.
if(ajax.checkReadyState(’body’, ’loading...’, ’loading...’, ’loading...’) == "OK")
{
document.getElementById(’body’).innerHTML = ajax.request.responseText;
}
Ajax.Request
This object is a general-purpose AJAX requester: it handles the life-cycle of the request, handles the boilerplate, and lets you plug in callback functions for your custom needs.
In the optional options hash, you usually provide a onComplete and/or onSuccess callback, unless you’re in the edge case where you’re getting a JavaScript-typed response, that will automatically be eval’d.
For a full list of common options and callbacks, see Ajax Options.
The only proper way to create a requester is through the new operator. As soon as the object is created, it initiates the request, then goes on processing it throughout its life-cyle.
var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
// notice the use of a proxy to circumvent the Same Origin Policy.
new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' });
else
notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' });
}
});
Issues when working with AJAX
AJAX and its pros and cons have been discussed elsewhere (Adaptive Path’s article and the Wikipedia entry are good starting-points) so there’s no need to do so again; instead this paper covers the main stumbling-blocks you’re likely to come across with AJAX: instantiating the necessary Javascript object, building the request, and using the response.
function getNewXMLHttpRequest() {
var obj;
try {
// For Internet Explorer.
obj = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {
try {
// Gecko-based browsers, Safari, and Opera.
obj = new XMLHttpRequest();
}
catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
obj = false;
}
}
return obj;
}
AJAX Timeouts with Prototype
I’ve been implementing some AJAX goodness in Mayday and other FastFrame apps lately. In my reading of the various pitfalls of AJAX one that popped up repeatedly was how to handle gracefully a network outage or the webserver going down. For example, Gmail’s chat handles it nicely. When I turn off my airport connection Gmail chat lets me know that it can’t contact the server and maybe my connection is down. Much better than an endlessly spinning hour glass, or worse, not letting the user know their action was never completed.
function callInProgress (xmlhttp) {
switch (xmlhttp.readyState) {
case 1: case 2: case 3:
return true;
break;
// Case 4 and 0
default:
return false;
break;
}
}
function showFailureMessage() {
alert('uh oh, it looks like the network is down. Try again shortly');
}
// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
onCreate: function(request) {
request['timeoutId'] = window.setTimeout(
function() {
// If we have hit the timeout and the AJAX request is active, abort it and let the user know
if (callInProgress(request.transport)) {
request.transport.abort();
showFailureMessage();
// Run the onFailure method if we set one up when creating the AJAX object
if (request.options['onFailure']) {
request.options['onFailure'](request.transport, request.json);
}
}
},
5000 // Five seconds
);
},
onComplete: function(request) {
// Clear the timeout, the request completed ok
window.clearTimeout(request['timeoutId']);
}
});
Creating a new ajaxObject
This AJAX snippet is a javascript object. You assign it to a variable the same way you assign a new Array(), or new Object(). This means you can have many variables, each one it’s own little, discrete AJAX handler. You can even make an array of Ajax objects if you so desire. (be aware however that most browsers will only process two requests at a time. You can declare and start as many ajax requests as you want but only two requests will be processed at a time and the other requests will patiently wait their turn until they can be processed).
When you create the variable assignment, you pass the URL you want that that Ajax object to call. (And remember, Ajax requests are bound to the same domain as the web page. If you’re on mydomain.com you’ll get an error if you try to make an Ajax request to theirdomain.com).
var myRequest = new ajaxObject('http://www.somedomain.com/process.php');
Basic Ajax Requests Using MooTools 1.2
Ajax has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made Ajax so simple that a rookie developer can get their dynamic pages working in no time.
<p>
02.
<a href="http://davidwalsh.name/dw-content/moo-basic-ajax-example.php" id="ajax-alert">Click here</a> to receive a special message from a PHP script via a javascript alert.
03.
</p>
04.
<p>
05.
<a href="http://davidwalsh.name/dw-content/moo-basic-ajax-example.php" id="ajax-replace">Click here</a> to populate the element below with the special message.
06.
</p>
07.
<div id="message-here">
08.
Special message will appear here.
09.
</div>
How to use Ext.Ajax.request with Response Text?
If we want to query something via ajax and show a response on the screen, we can use Ext.Ajax.request class of ExtJS. It provides a simple way to make Ajax requests with maximum flexibility. We will set the action url and get a response from action. Then, we will show the response on the screen. Let’s do it.
Firstly, I am writing the JSP page:
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<link rel="stylesheet" type="text/css" href="/xx/resources/extjs/css/ext-all.css">
<script type="text/javascript" src="/xx/resources/extjs/ext-base.js"></script>
<script type="text/javascript" src="/xx/resources/extjs/ext-all-debug.js"></script>
<script type="text/javascript">
Ext.onReady(function() {
function fn_AKExt( message, title ){
Ext.Msg.show({
title: title,
msg: message ,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.INFO
});
}
function fn_submitForm(button,event){
var f = Ext.getCmp('myFormPanel');
if( f.getForm().isValid() == true)
{
var startDate = Ext.getCmp('startDate');
var finishDate = Ext.getCmp('finishDate');
Ext.Ajax.request({
url : 'xxxxAction.do?MID=getReservableType',
method: 'POST',
params :{sd:startDate.value, fd:finishDate.value},
success: function ( result, request ) {
var jsonData = Ext.util.JSON.decode(result.responseText);
var resultMessage = jsonData.data.result;
fn_AKExt(resultMessage, 'Success');
},
failure: function ( result, request ) {
var jsonData = Ext.util.JSON.decode(result.responseText);
var resultMessage = jsonData.data.result;
fn_AKExt(resultMessage, 'Error');
}
});
}else{
alert("Tüm alanları doldurmadınız!");
}
}
var myFormPanel = new Ext.FormPanel({
labelWidth: 180,
id: 'myFormPanel',
frame:true,
title: 'Kampanya Tanım Formu',
bodyStyle:'padding:5px 5px 0',
width: 480,
defaults: {width: 170},
defaultType: 'textfield',
bodyBorder: false,
bodyStyle:'padding:5px 5px 0; border-width: 0px;',
monitorValid:true,
items: [{
xtype:'fieldset',
id : 'fieldset1',
title: 'xxx',
collapsible: false,
autoHeight: true,
autoWidth : true,
defaults: {width: 230},
defaultType: 'textfield',
waitMsgTarget: true,
waitMsg:'Loading',
items: [
new Ext.form.DateField({
fieldLabel: 'Start Date',
name: 'startDate',
format : 'd.m.Y',
readOnly :true
}),
new Ext.form.DateField({
fieldLabel: 'Finish Date',
name: 'finishDate',
format : 'd.m.Y',
readOnly :true
})
]
}
],
buttons: [{
text: 'Kaydet',
handler: fn_submitForm
}],
renderTo: 'content'
});
});
</script>
<table>
<tr >
<td valign="top">
<div name="content" id="content"></div>
</td>
</tr>
</table>

RSS Feeds
Feed Comment 




Leave Your Comments Below