Q1 field not valid

hushedsnailInternet και Εφαρμογές Web

12 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

139 εμφανίσεις

AJAX

Parts 1
, 2 and 3


Part I

Originally AJAX stood for Asynchronous JavaScript And XML, but now it stands for its own technology,
Ajax.

Ajax is a method of changing what appears on a page without a page reload. It is what is used in
googlemaps and all
the other Web 2.0 sites.

Prior to th
e introduction of Ajax, we used
i
nnerHtml
, which is supported by browsers but is
not

a w3c
standard.

It is still used, but DOM methods are preferred.


Because Ajax changes a web page without reloads there are accessib
ility issues (screen readers trigger
when a new page is loaded), as well as frustration with some users because they can’t save a result (e.g.
on googlemaps) and the back button doesn’t work as expected.

AJAX

1.

Preliminaries:

a.

InnerHTML

This is the content of

any HTML tag.

You may use
the
DOM to reset it.

Example: Suppose you have a tag


<span id=’Q1_message’


style=’text
-
color:red’>



</span>


Then your validation function could say


elmnt=document.getElementByID(‘Q1_message’);


//Note must start at document level.



if (
Q1 field not valid
)


{elmnt. innerHTML=


‘REQUIRED FIELD!’;}


else

//reset an
y previous error message



{elmnt.innerHTML=” “;}



InnerHTML is not a part of the w3c specification, even though it is supported


by IE, Safari and Firefox. This is because devices for assistive technology


(aural readers
, Braille readers etc.) can’t handle it.



The recommended method is to use
the
DOM to first remove the span node and


then insert a new span node. Evidently, the assistive device readers can


handle this (presumably with a page re
-
lo
ad.)



An alternative might be to use different style sheets for different devices and


then change to<em> or <strong> for fields with errors. I don’t know if this will


work or not.



b. Assigning functions


JavaScript allows yo
u to assign a function ( or your own ) to an object method.


Remember that objects also can be assigned new properties and methods by


accessing their definition/constructor with the
prototype
method.


See your JavaScript text, hour 6

p.94ff f
or more examples.


Example: You have some arrays and would like to have a function to multiply


each element by 10.


First you define your new function times10array.


Since it will be

a
method associated with a particular array, we will


use
this

to get a hold of the elements in that array.



function times10array ( )


{ for (i=0; i<this.length; i++) this[i] *= 10;}




Now we add a new method to the array object, and call that method


times10:



Array.prototype.times10 = times10array;



NOTES: We define our function first, in the usual way
.


Then we use protoype to add it to our object



with NO ( ) in that line where we add it.



This also works for user defined objects.




This also works (without the protype line) if an object


has the method defined
---

you are re
-
defining the


method. For instance, the default metho
d may do


nothing to allow re
-
defintion.



You have also seen this when you assign code to an


event handler:



onSubmit = ” “


(Quote marks are required here b/c onSubmit is in


an HTML tag, not in a JS script. The quote marks



serve to delimit the JS code in the tag.)








2.

And now….Ajax. Broad outline:

a.

You will need to open some communication between the client page and the server. This
is done
with an
XMLHttpRequest

object.

b.

The request:
Using that object you will send a request to the server(with a GET or a POST).


c.

The server will send back some infor
mation (either as a string or as an XML object)

d.

You use DOM access methods to change what appears on your page.


3.

Ajax


Slightly more detailed outline:

a.

The set
-
up: You will need to open some communication between the client page and the server.

This is done with an
XMLHttpRequest

object.

i.

You check to see if the browser is IE5/6

ii.

If the browser is IE7+ or any other browser you start a new XMLHttpRequest object;

if the browser is IE5/6 or any other browser you start a new ActiveX object

iii.

Either way

you give the object the same name


say
myAjaxReq
.


b.

The request: Using that object you will send a request to the server(with a GET or a POST).

i.

You use the
open( )
method of
myAjaxReq

to specify the URL on the server which has your
data and also if you
are using a GET or a POST (That information will go in open’s
parameters.)

ii.

In your open you will (almost) always ask for asynchronous communication, so your user
can do other things while waiting for Ajax to do its stuff. Asynchronous mode is set with
on
e of open’s parameters.

iii.

You use the
send( )
method

to send off the request.

For post requests, you will also put the information you are posting in send’s parameters

(& specify the content header coming back to you)
.


c.

The response:
The information returns

i.

Your
myAjaxReq

object has a

readystat
e

property which tells you where you are in the
cycle of setting up, sending, and receiving data.


You can examine
myAjaxReq
.readystate

ii.

Your
myAjaxReq

object has an event handler named
onreadystatechange

which fires
whenever
readys
t
ate,
the state of your communication channel
,

changes


e.g. it is now
ready.

You will need to assign to that event handler a function which does what you want with
the informa
tion that the server sends back.

myAjaxReq
.onreadys
tatechange=
myResponseFunc

iii.

We will process the information the server sent back

in the next step



i.e. write the code
for
myResponseFunc
.

d.

What you want to do:

Using document.getElementById or similar DOM methods you will get ahold of the part of the
page
you wish to change


Using either innerHtml or, more properly, DOM methods to get ahold of the nodes associated with
your element, you will change the values of the

element which appear on the page.

i.

You now need to write
myResponseFunc

which will do somethi
ng with what the server
sent back.

ii.

Typically there is an element of your HTML page whose text/value you wish to change.
You can grab it with e=document.getElementById(‘thisThing’).

iii.

The response from the server sent back either some text or an XML object.

iv.

If you sent a
GET

response then a string is returned and stored in the
responseText

property of
myAjaxReq
.

You may assign
myAjaxReq
.responseText to the text of an element e, to an array entry,
etc.

v.

If you sent an
POST

and specified a content type with

x
ml, then an XML object is
returned and stored in
responseXML
.

You may move around
myAjaxReq
.responseXML using DOM methods, finding something
you want and assigning it to the text or value child of the element e, to an array entry, etc.



4.

All the gory detai
ls:

We will read the following together:

a.

Your JavaScript text Hour 17, pp. 273
-
281

b.

The article at
www.devx.com/webdev/Article/33024/1954?pf=true

c.

The rest of Hour 17

d.

The w3c on the XMLHttpRequestObject at
http://www.w3.org/TR/XMLHttpRequest/


e.

The ALAX libraries
-

DoJo,Prototype, or script.aculo.us wo
uld be an appropriate place for further
investigaion
.

They are libra
ries of Ajax functions.

More can be found at
http://www.developer.com/xml/article.php/3645666/The
-
Twelve
-
Days
-
of
-
AJAX.htm

and on our Web Centric Resource
s

p
age
http://web.simmons.edu/~menzin/WebCentricResources.html


The w3c specs are at
http://www.w3.org/TR/XMLHttpRequest/


Equally dense info
rmation is at
https://developer.mozilla.org/en/xmlhttprequest



Part II

5.

Let us review what the article you read said:



AJAX

stands for Asynchronous JavaScript with XML.

It is used to download

code/data from a server to a client machine so that the client may change its page
appearance without needing to access the server again, that is without a page re
-
load.

This saves time for the client and bandwidth, but (a) it doesn’t work on all browsers

(e.g. not on some
mobile devices) (b) it doesn’t leave a client page which is reproducible in its last state
(c) they are tricky to
debug.

On the other hand, they are sexy and there are good libraries for Ajax available. (See 2e above and also
look at
Ajaxian.com)




AJAX works by using the
XMLHttpRequest

object which is built in to JavaScript.

This object is accessed slightly differently in IE5 and IE6 so we’ll use a special function to get a hold of the
object.


THIS IS IMPORTANT CODE:


A pretty
standard method is to see if there is an XMLHttpRequestObject (i.e. you are not using IE5 or 6)
and return it if there is, and otherwise get an ActiveX object.


<script type="text/JavaScript">


function sendRequest(){


var xmlHttpReq=init();




function
init
(){


if (window.XMLHttpRequest) {


return new XMLHttpRequest();


}


else if (window.ActiveXObject) {


return new ActiveXObject("Microsoft.XMLHTTP");


}


}


</script>





The XMLHttpRequest object has a pr
operty called
ReadyState

which keeps track of where you are in the
reque
st
-
response process. (See page

above for specifics).

This property takes values between 0 and 4, with 4 meaning the response has been received.




The object also has a
on
readystatech
ange

event which fires whenever the ReadyState value changes
---

and, of course, the first thing you will do is see what value it changed to. (You are looking for the 4.)

You will send this to be equal to the name of a function you designed that does your

stuff.




When a response is completed, the
responseXML

property gets set; it set
s

to
null

unless


-

the ReadyState is 4 and


-

the MIME type in the Content
-
Type header indicates you have an


XML respon
se (text/xml, application/xml or +xml)

Normally, when everything goes well, this has the response you are looking for in XML, and you can then
use DOM methods such as document.getElementByID(‘myID’) to manipulate the response.




There are two properties named
status

and
statusText

which may be accessed only when the
XMLHttpRequest object is in state 3 (receiving) or4 (loaded.).




In addition to these properties, the XMLHttpRequest object has a number of methods.

We now look at the
two most important ones.


open(meth, url)
opens an object. Here:

meth is the name of the method and it must be one of ‘GET’, ‘POST’, ‘HEAD’, ‘PUT’, or


‘DELETE’. These are all HTTP methods.


You know GET and POST from our work with for
ms.


HEAD is used to check to see if you have the most current version of a file (e.g. a


weather report) and it gets only the heading.

url is the name of the URL you are going to (relative addressing or absolute)

Actually you have open(m
eth, url, [sync[, userName[, Password]]]) and add the


optional parameters to synchronize (boolean), etc.

To see how this works, turn to p. 279 of your text.





send(parameterList)

sends your request to the server, once the ReadyState value is 1.

If there are no parameters to send, put
null

in the parentheses.



open() and send() for a GET

You will code:

myAjaxReq
=init()



//init is at the top of p.6

myAjaxReq.onreadystatechange=myResponseFunc;



//you have previously defined
myResponseFunc


myAjaxReq
.open(“GET”, scriptURL?URL_encoded_data

all in quotes
);




myAjaxReq
.send(null)


In the

example, from the devx.com
article we have

is:



var
cat
Id=encodeURIComponent(


document.getElementById("catalogId").value);


xmlHttpReq.open("GET", "validateForm?catalogId=" +
cat
Id, true);


Here the built
-
in JavaScript function encodeURIComponent( ) is used to take the
value

property of the
catalogId element and encode it so that blank spaces turn into +s etc.

Then that encode value is appended to the URL for the script validateForm and it is sent off with a GET.


You may read about encodeURIComponent( ) and its inverse decod
eURIComponent( ) at
http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp



open() and send() for a POST

When you send data with a POST you must also tell the receiving scrip
t to send the response back with
the appropriate type of data.


You will code:


myAjaxReq
=init()


//init is at the top of p.6

if (
myAjaxReq
)



{
myAjaxReq
.onreadystatechange = myResponseFunc;



//myResponseFunc has been previously defined




myAjaxReq
.open("POST", "scriptURL
.ext", true);




myAjaxReq
.setRequestHeader("Content
-
Type",

"application/x
-
www
-
form
-
urlencoded");




myAjaxReq
.send("name1=value1&name2
=value2");




}


NOTE: It is much more common to use a GET than a POST with Ajax.

More information of setRequestHeader may be found at
http://
www.computerworld.com/s/article/9002507/Hands_On_Understanding_AJAX?nlid=48&source=NLT_APP



Summary

You have seen how to
follow the steps below:



D
efine init() to get an XMXLHttpRequest object.



Assign a function to that object’s onreadystatechange event
handler



Write an open( ) command with the relevant data for a GET or a POST



Send off the request

(for a POST you must first setRequestHeader)



Know when a response comes back thru the onreadystatechange event handler


All that is left is to write the

function we will assign to onreadystatechange


a function which will test
readystate to be sure we have a completed, successful response and then will massage our web page.


Part III


More on the DOM

and InnerHTML

6.

InnerHTML

As explained on p.1 of this d
ocument, the innerHTML of
any HTML tag is its content.

Here are some examples showing how to use innerHTML to reset that content:

http://w3schools.com/ajax/tryit.asp?filename=tryajax_first


http://www.devx.com/webdev/Article/33024/1954?pf=true

at the very bottom

http://w3schools.com/ajax/tryit.asp?filename=tryajax_xml


http://w3schools.com/ajax/tryit.asp?filename=tryajax_callback


http://www.peachpit.com/articles/article.aspx?p=425820&seqNum=6


http://www.peachpit.com/articles/article.aspx?p=425820&seqNum=7

(whi
ch also uses the DOM)

http://www.xul.fr/en
-
xml
-
ajax.html#ajax
-
example

with its demo

http://www.xul.fr/ajax/demos.html

and the demos there (look at the source code!)


7.

The DOM in spades

Because innerHTML is not a w3c standard, the preferred method is to use the DOM to manipulate the web
page.

Firefox, Chrome and most other browsers come with a DOM inspector. This is usefu
l, as the DOM can be
tricky.

In addition, IE7 and earlier have spotty support for some DOM methods


see
http://www.webdevout.net/browser
-
support#dom

and
http://w3schools.com/dom/dom_mozilla_vs_ie.asp

As you know all X
ML documents have a root node, text,element, attribute, and comment nodes.

Let us look at
https://login.simmons.edu/cas/logout?service=https%3A%2F%2Femail.si
mmons.edu%2Fhorde%2Flogin.p
hp&horde_logout_token=E3AcxzLrF36lLSNBcK0P4nXc43g&app=horde&logout_reason=logout

and use
Firefox’s DOM Inspector.

Ditto for my home page
http://web.simmons.edu/~menzin/



Examine an
d discuss

http://w3schools.com/dom/dom_methods.asp

but warning about child nodes


getElementById and getElementByTagName are reliable


http://w3schools.com/dom/dom_nodes_get.asp


The code at
http://w3schools.com/dom/dom_nodes_set.asp

works in both FF and IE



http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php