Home
Home Page
Than differ id and class
Creation WAP of a page
Passions around AJAX are heated
Answers to often asked questions on XHTML and HTML
The sanction of the screen and marking of pages
Two styles ajax'?
Business Macromedia lives
XHTML+CSS. Advantages are obvious
Microformats
The semantic network based on microformats
Fonts and CSS
CSS from And up to I
Properties of the text
Illumination of the link
Change of a background in the table
Fixation of fonts on page with the help of the table of styles
Krossbrauzernoe alignment on the center
Polling with help AJAX
HTML
Links
 

Polling with help AJAX

You - me, I - you


The algorithm of carrying out of polling and the report of interaction of the client and the server will be now in detail considered. So, after loading the basic page, means JavaScript carry out GET-search without parameters to the server for reception of the initial data for carrying out of polling. The server returns them as XML the document of the following structure:



<poll>

<question> to you how much years? </question>

<choices>

         <choice>

<text> 10 </text>

</choice>

<choice>

<text> 20 </text>

</choice>

<choice>

<text> I do not remember </text>

</choice>

         <choice>

<text> And to you what for? </text>

</choice>

</choices>

</poll>


It is easy to notice, that the server passes a question and variants of the answer to him{it} to a client part of the application.


On the client there is a processing of the received information and its{her} conclusion to page. After the user will choose one of variants of the answer, one more search GET to the server is carried out. But this time, as parameter the index of the variant of the answer chosen the user is passed. The server saves a choice of the user and returns the new XML-document which contains statistics of answers:



<poll>

<question> to you how much years? </question>

<choices>

<choice>

<text> 10 </text>

<percent> 38 </percent>

</choice>

<choice>

<text> 20 </text>

<percent> 20 </percent>

</choice>

<choice>

<text> I do not remember </text>

<percent> 15 </percent>

</choice>

<choice>

<text> And to you what for? </text>

<percent> 27 </percent>

</choice>

</choices>

<totalVoted> 21760 </totalVoted>

</poll>


In this document the information on that has appeared, how much percent{interests} interrogated have chosen this or that variant of the answer, and how much all the person has taken part in polling. The client part of the application needs to deduce{remove} only the received data on page.



Realization


At once I shall result the link to an end result: polling. I want to emphasize, that I did not have problem{task} to make a universal script for carrying out of pollings. If you want to use the code resulted below you should modify it{him} that he corresponded{met} to your needs{requirements}. The given example has a minimum of functionality, but it is enough of it for an illustration of application AJAX for polling users of a site.


I shall not result a code of a server part of a considered{an examined} example. Yes he also is not important. I shall say only, that actually he does not save results of polling, and generates in their casual image. It is confident, that you cannot realize the server script returning simple XML-documents, and saving results of polling in a database or in a file on the server.


Now we pass to a client part. An initial code of page in a text format: poll.txt. If you confuse unfamiliar tegi (which a significant role do not play) can simply see{overlook} HTML a code of a working example.


The area of page on which the conclusion of the data in a course of polling will be carried out, is defined{determined} tegom div which has id = "poll". I shall not stop on service functions which return a copy of class XMLHttpRequest and carry out with the help of him{it} asynchronous search GET to the server. These functions have been described in previous clause{article}. We shall consider a new code:



// CallBack-function.

function processResponse () {

if (httpRequester.readyState == READY_STATE_COMPLETE) {

if (httpRequester.status == 200) {

processXmlResponse (httpRequester.responseXML)

} else {

var message = " Problem retrieving data. requestStatus = " + httpRequester.status + ". Message = " + httpRequester.statusText;

alert (message);

}

}

}


var isInit = true;


// Carries out processing the xml-document received from the server.

function processXmlResponse (xmlResponse) {

if (isInit) {

initPoll (xmlResponse);

isInit = false;

} else {

showResults (xmlResponse)

}

}


If at data acquisition from the server not mistakes have not arisen (i.e. httpRequester.status=200) to receive them it is possible with the help of property responseXML object of class XMLHttpRequest. Thus they are already treated not as the text, and as object XML DOM. After the data are received, they are passed procedure processXmlResponse which causes procedure of preparation of polling or a conclusion of result depending on that, the first it was a call or the second. We shall consider procedure initPoll:



// Creation on page of all polling necessary for carrying out

function initPoll (xml) {

var divElement = document.getElementById ("poll");

divElement.appendChild (document.createTextNode (getQuestion (xml))); // addition of a question on page

divElement.appendChild (document.createElement ("br"));

var choices = xml.documentElement.getElementsByTagName ("choice"); // reception of all variants of the answer from XML

for (var i=0; i <choices.length; i ++) {

var radioElement = createNamedElement ("input", "rdChoice"); // creation radio button

radioElement.setAttribute ("type", "radio");

divElement.appendChild (radioElement); // addition radio button on page

var choice = choices [i] .firstChild.firstChild.data; // poluenie a variant of the answer from XML

divElement.appendChild (document.createTextNode (choice)); // addition of a variant of the answer

divElement.appendChild (document.createElement ("br"));

}

divElement.appendChild (document.createElement ("br"));

var buttonElement = document.createElement ("input"); // creation of the button

buttonElement.setAttribute ("type", "button");

buttonElement.setAttribute ("value", " To vote! ");

buttonElement.onclick = vote; // addition obrabotchika onClick buttons

divElement.appendChild (buttonElement); // addition of the button on page

}


// Function returns a question taken, from the xml-document with help DOM

function getQuestion (xml) {

return xml.documentElement.getElementsByTagName ("question") [0] .firstChild.data;

}


Here all is transparent enough. First on page the element div, the having identifier "poll" is searched. Then in him{it} the question, variants of the answer, and the button is located, by pressing on which the voting procedure will be executed. New elements are created and added on page with help HTML DOM. The data from the XML-document received from the server, too are taken by means DOM. The unique moment which demands separate consideration, this creation of elements input such as "radio" with the help of function createNamedElement



Overcoming of features


As is known, realization JavaScript differs in different browsers and not always corresponds{meets} to standards W3C. Such discrepancy is accepted to name "features" of a browser. One of such features also should be overcome in a course of realization of a task in view.


For a choice of one variant of the answer to a question I used an element of management " radio button ". To unit some such elements in group, they need to appoint identical value of attribute name. I have chosen value "rdChoice". So, I created an element input and after that established at him{it} name, equal "rdChoice". The problem that Internet Explorer does not allow to establish value of attribute name after an element has already been created. What to do{make}? To bypass this bug, programmers Microsoft have made possible{probable} creation of the elements already having some people attributy. As you understand, take creation of elements is not described in the standard and supported only in IE. Function which creates elements with the set attribute name in any browser looks so:



// Function returns a new element with established attributom name

function createNamedElement (type, name) {

var element = null;

// Attempt to create an element in style IE. She will be unsuccessful in the majority of browsers

try {

element = document.createElement ('<' +type + ' name = " ' + name + ' "> ');

} catch (e) {

}

if (! element || element.nodeName! = type.toUpperCase ()) {

// For not IE; use of a standard method of creation of an element

element = document.createElement (type);

element.setAttribute ("name", name);

}

return element;

}



Returning to our rams


Now it is high time to consider procedure vote which is carried out when the user has chosen one of variants of the answer and has pressed the button " To vote! ".



function vote () {

divElement = document.getElementById ("poll");

var index = 0;

var selIndex =-1;

// Definition of an index of the chosen answer

var childs = divElement.childNodes;

for (var i=0; i <childs.length; i ++) {

if (childs [i] .nodeType == 1) {

if (childs [i] .getAttribute ("name") == "rdChoice") {

if (childs [i] .checked) {

selIndex=index;

}

index ++;

}

}

}

if (selIndex ==-1) {

alert (" Any of variants is not chosen! ");

return;

}

makeAJAXCall (sUrl + "? choice = " + selIndex);

}


Here too all is rather simple. Procedure defines{determines} an index of the variant of the answer chosen the user, and carries out asynchronous search to the server, passing parameter "choice". In the answer the server will return the XML-document with results of polling. This document will be processed by procedure showResults which under the maintenance{contents} is very similar to procedure initPoll:



// A conclusion to page of results of polling

function showResults (xml) {

var divElement = document.getElementById ("poll");

while (divElement.hasChildNodes ()) divElement.removeChild (divElement.lastChild); // we clear contents div'?

divElement.appendChild (document.createTextNode (getQuestion (xml))); // addition of a question on page

divElement.appendChild (document.createElement ("br"));

var choices = xml.documentElement.getElementsByTagName ("choice"); // reception of all variants of the answer from XML

for (var i=0; i <choices.length; i ++) {

var choice = choices [i] .firstChild.firstChild.data; // reception of a variant of the answer from XML

var percent = choices [i] .childNodes [1] .firstChild.data; // reception of percent{interests} voted from XML

divElement.appendChild (document.createTextNode (percent + " % - " +choice)); // addition of result

divElement.appendChild (document.createElement ("br"));

}

divElement.appendChild (document.createElement ("br"));

// Reception of quantity{amount} voted

var totalVoted = xml.documentElement.getElementsByTagName ("totalVoted") [0] .firstChild.data;

divElement.appendChild (document.createTextNode (" All has voted: " +totalVoted)); // addition on page

}


In this clause{article} I have told, how it is possible to organize polling of users with use of technology AJAX. I hope, this example will help you at creation of pollings on your site.