|
Using XML: A PHP Developer's Primer, Part 2
Adam Delves
Sending a Request
To send an HTTP request using the XMLHTTP object, we need to first call
the open function with three parameters:
XmlHTTP.open(method, uri, async);
- method – this should be either 'get' or 'post'. For a get request, data to be passed to the script is appended to the URI using a query string in the form: uri.php?var1=value1&var2=value2. For a post request, the data is passed to the script in the HTTP request body. We use the uriEncodeComponent function to url encode the data to be sent.
- uri – the path to the receiving script, relative to the current page (for reasons of security the open method will only open a document within the same domain as the current document).
- async – tells us whether the request should be
asynchronous.
When set to true, the request for the document is sent and script
execution continues immediately. If set to false, the script waits
until the response has been fully received. It is advisable in most
cases to
set this to true, as a slow server could cause the user interface to
hang.
To send the request, we need to call the send function. Once a response
is received, the responseText property will contain the text sent by
the server side script in the HTTP response body. The location at which
this property is available is dependent on whether the request was
synchronous or asynchronous. With a synchronous request, the script
waits for the response before continuing, therefore, the responseText
property is available immediately after the the call to send. In
contrast, the script does not wait for the response if the request was
asynchronous. Instead, the XMLHTTP object fires the onreadystatechange
event. Each time the event is fired, the readyState property of the
XMLHTTP has changed. A readyState value of 4 signifies that the
response has been fully received and the responseText property contains
the
HTTP response body.
Synchronous Request
xmlHTTP.open('get', uri,
false);
xmlHTTP.send(null);
alert(xmlHTTP.responseText);
Asynchronous Request
xmlHTTP.open('get', uri,
true);
xmlHTTP.onreadystatechange
= function ()
{
if(xmlHTTP.readyState == 4)
{
alert(xmlHTTP.responseText);
}
};
xmlHTTP.send(null);A value of null is always
supplied as the first argument to the send
function in the case of a get request. In a post request, the data is
sent
in the body of the request--this is done by passing a url-encoded
string to the send function instead of null.
Parsing the Response
In our email validation
application, we will be using asynchronous
requests and assigning a generic function to the onreadystatechange
event. This function will parse the response, validate it and use the
context supplied by the validation script to call the appropriate
function to deal with the response.
Javascript:
Javascript:
function parseResponse()
{
if (xmlHTTP.readyState != 4) {
/* the
request is not complete */
return;
}
var responseArray =
xmlHTTP.responseText.split(';');
var response =
Array();
if (responseArray.length != 3) {
/*
response is invalid */
return;
}
/*
load the response into a logical
associative array */
response['status'] =
parseInt(responseArray[0]);
response['data'] = responseArray[1];
response['context'] = responseArray[2];
/*
decide what to do based on the response
context */
switch(response['context']) {
case
'validate':
validateCallback(response);
break;
case
'verify':
verifyCallback(response);
break;
case
'invalid':
// return everything to its
original state and start over
startupState();
validateAddress();
break;
case
'unknownerror':
// something is wrong - so
we
are going to fall back
btnSubmit.removeAttribute('disabled');
txtEmail.onchange = null;
verify.style.display = 'none';
break;
}
}
This function will be called each
time the readstatechange event is
fired. Note that the Ajax part of the application is disabled if an
unknown error occurs. This ensures that the user can still submit the
form if email validation is not functioning. It is important to plan
for failure in any application, but more so in Ajax applications. Users have become
accustomed to submitting forms and presenting them with an
unsubmittable form is likely to cause frustration as the user may not
realize that any communication has been made with the server.
Validating the Email Address
Validating the email address is
done in two parts. The validateAddress
function is assigned to the onchange event handler of the email input
box. This event is fired each time a change is made to the contents by
the user. The validateAddress function performs the HTTP request and
sends the appropriate information such as the email address and the ID
in the query string.
Javascript:
Javascript:
function validateAddress()
{
var email = theForm.email.value;
var id =
parseInt(theForm.email_id.value);
startupState();
if (email != '') {
/* add
the email address to the query string */
var
dataString
= 'email='
+ encodeURIComponent(email);
if (id
> 0)
{
/* if an ID is set, add
that
too */
dataString += '&id=' +
id;
}
} else {
/* no
email entered, do nothing */
return;
}
/*
send the request */
xmlHTTP.open('get', emailValidate +
'validate&'
+ dataString,
true);
xmlHTTP.onreadystatechange
=
parseResponse;
xmlHTTP.send(null);
}
function
startupState()
{
verify.style.display = 'none';
verifyMsg.innerHTML = '';
txtVerify.removeAttribute('disabled');
btnVerify.removeAttribute('disabled');
btnVerify.innerHTML = 'Verify';
btnSubmit.setAttribute('disabled',
'disabled');
emailMsg.innerHTML = '';
theForm.email_id.value = '';
theForm.v_code.value = '';
}
I mentioned earlier that we are
using asynchronous requests. Therefore
the second part of the email validation takes place when the response
has been received from the server. The validateCallback function is
called when the server responds with a 'validate' context. If
validation was successful, the verification box is displayed.
Javascript:
Javascript:
function validateCallback(response)
{
if (response['status']) {
/* the
email address is valid and a verification email has been sent */
emailMsg.style.display = 'none';
verify.style.display = 'inline';
verifyMsg.innerHTML = '<b>An Email
containing
your verification code has been sent to this address. Please Enter it
before continuing.</b>';
theForm.email_id.value = response['data'];
} else {
/* the
email address was invalid */
verify.style.display = 'none';
emailMsg.innerHTML = '<b>You have
entered an
invalid email address. Please correct it before
continuing.</b>';
emailMsg.style.display = 'block';
theForm.email.focus();
}
}
| Comments: | ||
No Messages FoundYou can post questions/corrections/feedback here
| ||
|
If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly. | ||


