Friday, November 28, 2008

Calling Struts Action by Javascript

To call a struts action by Javascript on an event, you need to write a function which is invoked when the event occurs and this function makes an AJAX call. The AJAX call can send a request to the same URL which is provided in action attribute of form tag or html:form tag.

e.g. In case your action URL is something like
"/registerUserAction.do?action=forgetPasswordForward"
that you provide in action attribute of html:form, you can pass the same url to the mentioned code snippet below:


function makeRequest(url, callbackfunction)
{
var http_request = getXMLHttpObject();
url = url + "isComingFromAjax=true";

if (url.indexOf('?') != -1)
{
url = url + "&" ;
}
else
{
url = url + "?" ;
}

url = url + "isComingFromAjax=true";
http_request.onreadystatechange = callbackfunction;
http_request.open('POST', url.substring(0, url.indexOf('?')), true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(url.substring(url.indexOf('?') + 1));
}

Some of points to be considered in given code snippet:
1. callbackfunction is the function which will be invoked when response is received
2. "isComingFromAjax=true" parameter has been added as a extra parameter to differentiate between the normal action request and the AJAX request to do any special handling on the server side.

I have not covered details of creating XMLHttpRequest Object and other AJAX related things assuming you know it. You can write the logic for handling the response received from server in callbackfunction.

No comments: