We present a few AJAX tricks and a quick introduction to Prototype. Examples taken from:
- Idea: Instead of having user click "submit", which
triggers page refresh, write code that does an XHR submit on
the
onblur
event.
- Give the desired elements the ids "tarea" and
"tfield".
onblur
event is triggered when user moves
away from that element (tab, click).
var formObj = null;
var formObjTyp = "";
var request=null;
window.onload=function(){
var txtA = document.getElementById("tarea");
if(txtA != null){
txtA.onblur=function(){
if (this.value) { getInfo(this);}}; }
var tfd = document.getElementById("tfield");
if(tfd != null){
tfd.onblur=function(){
if (this.value) { getInfo(this);}}; }
}
function getInfo(obj){
if (obj == null ) { return; }
formObj=obj;
formObjTyp =obj.tagName;
if(formObjTyp == "input" || formObjTyp == "INPUT"){
formObjTyp = formObjTyp + " "+formObj.type;
}
formObjTyp = formObjTyp.toLowerCase();
var url = "http://www.parkerriver.com/s/webforms?objtype="+
encodeURIComponent(formObjTyp)+"&val="+ encodeURIComponent(obj.value);
httpRequest("GET",url,true);
}
function handleResponse(){
try{
if(request.readyState == 4){
if(request.status == 200){
var resp = request.responseText;
if(resp != null){
var func = new Function("return "+resp);
var objt = func();
if(formObjTyp == "textarea"){
if(formObj != null){
formObj.value = objt.Form_field_type +" character count: "+objt.Text_length+"\nWord count: "+
objt.Word_count+"\nServer info: "+objt.Server_info;
}
} else if(formObjTyp == "input text"){
if(formObj != null){
formObj.value = objt.Form_field_type +" # characters: "+objt.Text_length+" Word count: "+objt.Word_count; }
}
}
} else {
alert(
"A problem occurred with communicating between the XMLHttpRequest object and the server program.");
}
} } catch (err) {
alert(err.name);
alert("It does not appear that the server is available for this application. Please"+
" try again very soon. \nError: "+err.message);
}
}
function initReq(reqType,url,bool){
try{
request.onreadystatechange=handleResponse;
request.open(reqType,url,bool);
request.send(null);
} catch (errv) {
alert(
"The application cannot contact the server at the moment. "+
"Please try again in a few seconds." );
}
}
function httpRequest(reqType,url,asynch){
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
} else if (window.ActiveXObject){
request=new ActiveXObject("Msxml2.XMLHTTP");
if (! request){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
if(request){
initReq(reqType,url,asynch);
} else {
alert("Your browser does not permit the use of all "+
"of this application's features!");}
}
- Create and send a request with:
var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText.match(/href="http:\/\/" href="http://prototypejs.org/"
title="Linkification: http://prototypejs.org/">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' });
},
parameters: parametersObject, postBody: uploadStuff, requestHeaders: object, onComplete: function (t) {
},
onFailure: function (t) {
}
});
- If you send back javascript, it will be automatically
eval
ed.
- To keep an eye on all XHR calls use the
Ajax.Responders.register
or unregister
.
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
}
});
- If you are sending back XHTML to put in the page then:
new Ajax.Updater('items', '/items', {
parameters: { text: $F('text') },
insertion: Insertion.Bottom
});
- If you want to keep polling:
new Ajax.PeriodicalUpdater('items', '/items', {
method: 'get',
frequency: 3,
decay: 2
});
- Easy way to fill in the blanks:
var myTemplate = new Template('The TV show #{title} was created by #{author}.');
var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };
myTemplate.evaluate(show) [120]