Archive for September, 2008

Ajax example

September 29, 2008

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

Handling Ajax Response

September 27, 2008

when you are sending request to the server, you can get a response in the below specified function.
onreadystatechange = functionname

functionname – is a javascript function to handle the ajax response.

function definition should be like this.

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

Let’s see what this function should do. First, the function needs to check for the state of the request. The request readyState has 4 values is as follows.

  • 0  – uninitialized
  • 1  – loading
  • 2  – loaded
  • 3  – interactive
  • 4  – complete

If the state has the value 4, that means the full server response is received and it’s OK to continue processing it.
if (req.readyState == 4) { // response is received.}

Second thing,  is to check the status code of the HTTP server response. For that, we will look at value 200 for OK response.Otherwise there has to be some problem with the request.

if (req.status == 200) { //request status is OK}

After the above two cases are OK, then you have to process the response data based on your requirement. You have two options to access that data

responseText – this will return the server response as text
responseXML – this will return the response as an XML document(you can parse the XML and get the data using javascript DOM functions)

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

Google – 10th Birthday

September 27, 2008

Google celebrates his 10th birthday today. Really a awesome one.

In 1996, Larry Page and Sergey Brin introduced a new search engine tool called BackRub. After a year(15th, sep 1997) they decided to change the tool name, that is Google – a word from Googol(a mathematical term represents 1 followed by 100 zero’s).

Now the tool really Rocks..!!

See here for more information’s about Google History and its timeline.

Now, Google has lots of web tools(Docs, Calendar, etc.,). In that Google Search is the one am using daily. Thanks to Google for introducing such a powerful search tool.

How to execute the scripts in AJAX response(HTML with scripts)

September 26, 2008

Send an ajax request and get the response as html. Scripts present in that response html are not executed automatically. We have to manually execute the script after getting the response. Two ways to do the same.

  • use eval command to execute the codes in script tag.
  • read the scripts in response and append into the HEAD tag.

In the above two methods, Sometimes the eval command could not work as expected. So i recommend the second one is the best. Also if the script codes getting longer its better to append all those scripts to head tag. Lets see how to execute the script in both the way.

invokeScript(contentId) – method for executing script separately.
scenario :  send a Ajax request, response is HTML with some scripts – scripts in response HTML should not loaded automatically.
to overcome this issue, we used this method to load the scripts separately.

Method 1 : using eval command.

function invokeScript(divid)
{
var obj= divid.getElementsByTagName(“SCRIPT”);
var len = obj.length;
for(var i=0; i<len; i++)
{
eval(obj[i].text);   // execute the scripts.
}
}

Method 2 : appending scripts to HEAD tag

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);
}
}
}

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

AJAX – POST request

September 25, 2008

If you want to send data with large size (GET allows up to 255 characters only). you can use POST method.
Mostly, POST methods are used in HTML forms. Let see the syntax of open & send method.

open(param1, param2, param3);

param1 – specifies HTTP request method (GET, POST, HEAD, etc..,)
param2 – action url,  the page you are requesting.
param3 – specifies an asynchronous request if its true

send(params);

params –  passing parameters of the POST request, in the form of query string.
Note : this parameter has null value when you send a request as GET method.thats the only difference.

Set the below MIME type for any POST requests made via Ajax.

setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

The below two lines are optional. If you want you can specify it.

setRequestHeader(“Content-length”, params.length);
setRequestHeader(“Connection”, “close”);

Example

sendAjaxRequest(“projectdetails.jsp”, “projectid=1024&module=accounts”, “showdetails”);

function sendAjaxRequest(url, params, divid)
{
url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.open(‘POST’, url, true);
req.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
req.setRequestHeader(“Content-length”, params.length);
req.setRequestHeader(“Connection”, “close”);
req.onreadystatechange = function(){ processResponseHTML(req, divid) };
req.send(params);
}

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

IE browser issue while sending ajax requests.

September 24, 2008

IE browser does not send ajax request if the url is same, simply get the results from cache. To avoid this and make a new request, we should append a no-cache parameter to each ajax request url.

getNoCacheValue(url) – method for dynamically getting current time in milliseconds and append that value to no-cache parameter.

function getNoCacheValue(url)
{
var d = new Date();
var appendstring = (url.indexOf(“?”) != -1) ? “&” : “?”;
var nocachevalue = appendstring + “no-cache=” + d.getTime();
return nocachevalue
}

sendAjaxRequest(url, divid) – method to send a ajax request and write the response text to given divid. In this method, getNoCacheValue(url) method called to avoid the cache problem in IE browser.

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);
}

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

IE browser failed to execute scripts in ajax response – https://manikandanmv.wordpress.com/2008/10/18/ie-browser-failed-to-execute-scripts-in-ajax-response/

AJAX – Asynchronous JavaScript And XML.

September 23, 2008

AJAX is a technique for creating web applications more interactive & responsive. It makes all applications better, faster and more user-friendly. AJAX is based on JavaScript and HTTP requests. AJAX uses asynchronous data transfer between the web client(browser) and the web server. You can get text/xml type of AJAX responses.


advantages.

  • increase the speed and usability of an application’s web page by updating only a part of the page.
  • webclient has to be more interactive and getting fast response.
  • reducing the number of requests to server. because css, js are loaded only once.

disadvantages

  • browser history not added
  • difficult to bookmark a page.
  • all browsers must enabled the javascript options.

Lets see how to implement this.

getXMLHttpRequest() – common method to get an instance of  XMLHttp request, using this to send a request as Ajax request

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;
}

sendAjaxRequest(url, divid) – method to send a ajax request, response is HTML and write the response text to given divid.

url – to send a request to the server (Ex: /testing.jsp)

function sendAjaxRequest(url, divid)
{
var req = getXMLHttpRequest();
req.onreadystatechange = function(){ processResponse(req, divid) };
req.open(‘GET’, url, true); // GET type request.
req.send(null);
}
function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=req.responseText;
}
}
}

Ajax Example – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

How to execute case insensitive query in MySQL

September 20, 2008

Most of you came across this problem when executing query. Creating tables in proper case and access the same tables in lowercase.This should return error in some OS environment.I will explain below.

create table ProductDetails(ProductName varchar(50), Version varchar(10));

select * from productdetails;

The above query will work fine when execute in mysql in windows environment. But the same is failed to process in linux environment mysql. Because most linux operating systems are case sensitive so based on that database or table names are case sensitive.

To solve this problem. Use the –lower_case_table_names parameter to start the  mysql dameon. This parameter will ensure that the mysql will process the database or table names in case insensitive.

select * from productdetails;

select * from ProductDetails;

After setting the above param. The above two queries will work fine.