Step 3: Here we modify the step1.htm file to support AJAX style asynchronous form submission via the XMLHttpRequest object. Copy the file step1.htm to step3.htm and change the following: (See Listing B.)

Listing B


  1. Change the submit button to a button type.
  2. Add an onclick event hander for the button.
  3. Add the JavaScript event handler function.
  4. Add the XMLHttpRequest call back routine.

At this point I'll explain the importance of the code in Listing C.

Listing C
<if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if (window.ActiveXObject)


The first line of code I'd like to draw attention to is the code that creates the XMLHttpRequest object. This code utilises different instantiation styles depending on the browser type. Mozilla, Firefox and Safari all implement the XMLHttpRequest as an intrinsic object whereas Internet Explorer implements it as an Active X control. Note this code does not handle any errors; to do that I would wrap the whole thing in a try/catch block and handle any errors gracefully.

Next up is the code that handles the server response. (see Listing D).

Listing D
<Hhttp.onreadystatechange = function()
{
  if(http.readyState == 4)
    alert(“Server Response Was: “ +
      http.responseText);
};>


This is achieved through the use of an anonymous function assigned to the ReadyStateChange event of the of XMLHttpRequest object. The ReadyStateChange event fires when the XMLHttpRequest object changes state, or when various network events happen. One event is when data arrives from the remote host to the client. Upon data arriving at the client from the server, this handler simply prompts the user with the server response. Note this event handler is only necessary for asynchronous requests.

Now we arrive at the business end of the demonstration (see Listing E).

Listing E
<Hhttp.open(‘POST’, ‘saveData.jsp’, true);
  http.setRequestHeader(‘Content-Type’,
    ‘application/x-www-form-urlencoded’);
      http.send(“DATA=” + document.getElementById(‘DATA’).value); >

Here we perform that actual work of sending data to the server. Each line of code performs the following:

  1. Open a HTTP connection to the server. Parameters are HTTP call type, URL and true for asynchronous or false for synchronous connections.
  2. Set the content type for POSTed form data (omit for GET, HEAD, etc).
  3. Send the data stream over HTTP to the host.


That wraps up the demonstration of AJAX application development. In my next article I will demonstrate the AJAX solution for another common Web development problem; avoiding page refreshes with dependent select boxes. A common issue with Web page design is how to avoid a page refresh when a change in one element causes another element to have to change its data.

AJAX Support
Nowhere else has the effect of proprietary closed standards been more visible than with Web browsers. So it's a rare occasion when a Web technology enjoys cross platform support like AJAX has. The core object in AJAX is XMLHttpRequest, which is well supported in Internet Explorer, Gecko (Mozilla, Firefox), Opera, KHTML, and Safari. AJAX is also only a client-side consideration, which means it is server neutral. AJAX works just as easily with Java, C#, PHP, Perl or C++ on Windows, Linux, or UNIX.

The future of AJAX?
Client-side call-backs are a hot topic at the moment and this is set to only increase as application server vendors realise the huge potential of this interface design technique. Microsoft has embraced client-side call backs with ASP.NET 2.0 with ClientScriptManager that make client call backs a breeze to implement. Other vendors will play catch up over time.

A quick note on security
Most browsers including Microsoft Internet Explorer and Mozilla FireFox disallow HTTP connections to hosts other than the host where the script was loaded from. To allow scripts to post data to non-originating hosts you need to set the appropriate settings in your individual browser.

Do you need help with AJAX? Gain advice from Builder AU forums

Related links

Comments

1

Phil Cohen - 12/10/05

How would you submit a form that is set as multipart/form-data instead of application/x-www-form-urlencoded. Is this possible? I would like to upload images as well as the various text fields using AJAX. We are using ASPUpload at the server end so it needs the multipart/form-data type of form using the post method. Any info would be appreciated.

» Report offensive content

2

vipin deshwal - 21/09/06

It is very good site for best intro information and exmpiles. its write getway for bigners.

» Report offensive content

3

Atul - 06/12/06

Right i dont no how to run and which environment will use for writing the ajax program. i want to use ajax in aps.net

» Report offensive content

4

Reza - 08/12/06

Not working properly

» Report offensive content

5

radha - 26/01/07

Thanks phil,
I have the same question. I want to upload files using ajax without refreshing. I don't know how to send multipart/form data and retrieve the fileItems using apache's FileUpload utility.
Please if someone could elaborate I would really appreciate it.

Thanks in advance.

» Report offensive content

6

Prakash - 14/02/07

I want to upload files using ajax without refreshing

» Report offensive content

7

Andrew - 03/05/07

Can someone tell me / show me how to upload images using ASPJpeg? I already use ASPJpeg along with ASPUpload and it works great, but I would like to redesign my control panel using AJAX. If anyone could help me out I would really appreciate it. Thanks in advance!

» Report offensive content

8

mahesh_60489 - 17/07/07

it is the best site which gives detailed information. It is the right gateway for beginners.thank u.

» Report offensive content

9

utpal mondal - 20/08/07

How to remove race condition of ajax.

» Report offensive content

10

dfd - 13/09/07

11

Ananth - 15/10/07

Hi friends when i use ajax with DHTML or table or layer or div Ajax not proporly working here i paste my code if any one knows help me.... mobile 9994264662.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="field.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:200px;
height:115px;
z-index:1;
}
-->
</style>
</head>

<body>
<script src="hrcmvalidation.js"> </script>
<script type="text/javascript" language="javascript">
var http_request = false;
function makeRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url + parameters, true);
http_request.send(null);
}

function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}

function get(obj) {
var getstr = "?";
for (i=0; i<obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == "INPUT") {
if (obj.childNodes[i].type == "text") {
getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
}
if (obj.childNodes[i].type == "checkbox") {
if (obj.childNodes[i].checked) {
getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
} else {
getstr += obj.childNodes[i].name + "=&";
}
}
if (obj.childNodes[i].type == "radio") {
if (obj.childNodes[i].checked) {
getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
}
}
}
if (obj.childNodes[i].tagName == "SELECT") {
var sel = obj.childNodes[i];
getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
}

}
makeRequest('get.php', getstr);
}
</script>
<br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>
<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
<select name="select" class

Offensive content reported

12

Prabhu - 03/05/08

I am the beginner in ajax.so give me some guidelines how to develop

ourselves ajax.How to start working in ajax..and tell me the easy to

learn more in ajax

document.httrequest("beginnner")

» Report offensive content

13

Priti - 02/01/09

Really helpful for freshers ,how to leaen ajax

» Report offensive content

14

brijal - 21/11/09

hi,, i am getting a n error in my javascript that ajax is not defined.....
so can anybody tell me bout that solution...........



code is given below..

function handleGoToCart() { document.location = live_site + '/index.php?option=com_virtuemart&page=shop.cart&product_id=' + formCartAdd.product_id.value ; }

function handleAddToCart( formId, parameters ) {
formCartAdd = document.getElementById( formId );

var callback = function(responseText) {
updateMiniCarts();
// close an existing mooPrompt box first, before attempting to create a new one (thanks wellsie!)
if (document.boxB) {
document.boxB.close();
clearTimeout(timeoutID);
}

document.boxB = new MooPrompt(notice_lbl, responseText, {
buttons: 2,
width:400,
height:150,
overlay: false,
button1: ok_lbl,
button2: cart_title,
onButton2: handleGoToCart
});

setTimeout( 'document.boxB.close()', 3000 );
}

var opt = {
// Use POST
method: 'post',
// Send this lovely data
data: $(formId),
// Handle successful response
onComplete: callback,

evalScripts: true
}

new Ajax(formCartAdd.action, opt).request(); <!--(here i got error)-->
}

» Report offensive content

14

brijal - 21/11/09

hi,, i am getting a n error in my javascript that ajax is not defined..... so can anybody tell me bout ... more

13

Priti - 01/02/09

Really helpful for freshers ,how to leaen ajax ... more

12

Prabhu - 05/03/08

I am the beginner in ajax.so give me some guidelines how to develop ourselves ajax.How to start working in ajax..and tell ... more

Log in


Sign up | Forgot your password?

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!