Ajax example


I put all codes together for better understanding of AJAX. Example for sending a Ajax GET request.

client-side file
test.html The file you have to invoke the ajax request and see the response.
<html>
<script src=”ajax.js” language=”javascript”></script> // load the below js file.
<body>
<table>
<tr><td>
<a href=“javascript:void(0);” onclick = “sendAjaxRequest(‘/test.jsp?prod_id=123’, ‘showdetails’)“> click here to see Java related books</td></tr>
<tr><td><a href=“javascript:void(0);” onclick = “sendAjaxRequest(‘/test.jsp?prod_id=124’, ‘showdetails’)“> click here to see Ajax related books</td></tr>
</table>
<div id=”showdetails”></div>
</body>
</html>

ajax.js – the following scripts are written in a separate file and named as ajax.js

/* common method to get XMLHttp request object */
function getXMLHttpRequest()
{
var req;
if (window.XMLHttpRequest) { // For Firefox, Mozilla, Safari, …
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // For IE
try {
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e) {
try {
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e) {}
}
}
return req;
}

/* method for dynamically getting current time in milliseconds and append that value to no-cache parameter
* IE browser does not send ajax request if the url is same, simply get result from cache
* to avoid this and make a new request, we append no-cache param to each ajax request.
*/
function getNoCacheValue(url)
{
var d = new Date();
var appendstring = (url.indexOf(“?”) != -1) ? “&” : “?”;
var nocachevalue = appendstring + “no-cache=” + d.getTime();
return nocachevalue
}

/* method to send a ajax request, and write the response text to given divid. */
function sendAjaxRequest(url, divid)
{
url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.onreadystatechange = function(){ processResponse(req, divid) };
req.open(‘GET’, url, true);
req.send(null);
}

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=req.responseText;
invokeScript(document.getElementById(divid));
}
}
}

/* method for executing script separately.
* (scenario :  send a Ajax request, response is HTML with some scripts – scripts in response HTML should not load )
* to overcome this issue, we used this method to load the scripts separately.
*/
function invokeScript(divid)
{
var scriptObj = divid.getElementsByTagName(”SCRIPT”);
var len = scriptObj.length;
for(var i=0; i<len; i++)
{
var scriptText = scriptObj[i].text;
var scriptFile = scriptObj[i].src
var scriptTag = document.createElement(”SCRIPT”);
if ((scriptFile != null) && (scriptFile != “”)){
scriptTag.src = scriptFile;
}
scriptTag.text = scriptText;
if (!document.getElementsByTagName(”HEAD”)[0]) {
document.createElement(”HEAD”).appendChild(scriptTag)
}
else {
document.getElementsByTagName(”HEAD”)[0].appendChild(scriptTag);
}
}
}

test.jsp – write some logics here for showing data to client. Actually, this should not recommended to write business logics in jsp file. For learning period, you can do it.

in this file, get the request parameter value of product id (prod_id) and to show the product details of that id by querying the database. The area which you can your own logic/business logic comes here.

for example, i simply write the logical steps of retrieving product details of given product id.

  • get the prod_id value from request. using method request.getParameter(“prod_id”);
  • use prod_id as input to query the product database and retrieve the result. (select productname, description, price from ProductDetails where product_id=<<prod_id value get from request>>)
  • design your own way to show the retrieved product details.

Want to read basics of Ajax, click this link https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

Advertisements

Tags: , , , , ,

2 Responses to “Ajax example”

  1. Nkhil Says:

    Thank you very much for the replay. Actually i was asking about the server script that generate the XML file. I’m using PHP. Finally i was able to a create a file in php that reads the data base and converts the same to XML so that the Ajax xml response can get the data.. Now I have one more doubt if you don’t mind… How to show and hide HTML element(like tables and buttons) using javascript , from displaying in a page.I tried using getElementById(‘up’).style.display =’none’ this will hide the element however i dont know the code to show the element.

  2. manikandanmv Says:

    For your second question(How to show and hide HTML element?)
    answer is here https://manikandanmv.wordpress.com/2008/11/06/how-to-show-or-hide-the-html-elements/

    Soon will write a blog about “server side code for generate an XML file” and that will answer your first question. Will update you on this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: