Archive for October, 2008

Fade out ajax response status message

October 31, 2008

Successfully received the response from the server, It would be better if you can show that status to end-user. Used the property opacity for fading out the color., Depends on browser the opacity property is different.

Firefox browser supports property opacity:x – value x range from 0.0 to 1.0 (lower value makes more transparent).

IE browser uses filter: alpha(opacity=x) – value x range from 0 to 100.

The logic for fading out is set the time interval for periodically reduce the value of opacity property , so that the color gets transparent then it looks like a fading out.
Javascript functions setInterval & clearInterval are used for setting and clearing the time intervals respectively. Lets see the below example.

Example

fadeout.jsp

<html>
<body>
<script src=”fadeout.js” language=”javascript”></script>
<!– div to show the status message of ajax response –>
<div id=”statusmsg”  style=”background-color:green;opacity:.30;filter: alpha(opacity=30);”></div>
<a href=”#” onclick=”javascript:sendAjaxRequest(‘/storedb.do?prodid=1200&productname=ajax’, ‘statusmsg’);”>click to save</a>
</body>
</html>

fadeout.js

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=”Data Saved Successfully”;
setTimeout(“FadeOut(‘”+divid +”‘)”,5000); // added code for showing status message after 5 seconds.
}
}
}

/*
function for finding browser name. Because IE browser rendering a page differently. So this method will be useful for finding & writing browser specific javascript code
*/

function isIEBrowser()
{
var browsername = navigator.appName;
if( browsername == “Microsoft Internet Explorer” )
{
return true;
}
return false;
}

/*
method for calling fadeout
set the time interval for reducing the opacity value periodically.
*/
var intervalid;
function FadeOut(divid)
{
if(isIEBrowser()){
intervalid = setInterval(“decreaseOpacityForIE(‘”+divid+”‘)”,100);
}else{
intervalid = setInterval(“decreaseFading(‘”+divid+”‘)”,100);
}
}

// for IE Browser only
function decreaseOpacityForIE(divid)
{
var divobj = document.getElementById(divid);
if(divobj ){
divobj .filters.alpha.opacity=parseFloat(divobj .filters.alpha.opacity)-2;
if (divobj .filters.alpha.opacity <= 0 ){
clearInterval(intervalid);
}
}
}

// for other browsers – Firefox/Netscape
function decreaseOpacity(divid)
{
var divobj = document.getElementById(divid);
if(divobj ){
divobj.style.MozOpacity=parseFloat(divobj.style.MozOpacity)-0.02;
if (divobj.style.MozOpacity <= 0){
clearInterval(intervalid);
}
}
}

setTimeout(javascript stmt, milliseconds) –  execute that javascript statement after specified milliseconds intervals.

If you are new to Ajax see the below links to learn basics.

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/

Advertisements

Ajax File Upload

October 24, 2008

Normally its not easy to upload a file in ajax request. Even form input parameters are sending manually, you can read here for more details. With the help of iframe its possible for uploading a file(any format : .txt, .jpg,..) to the server without refreshing the entire page as like ajax. Lets see the example of how to do.

Example.

ajaxfileupload.jsp

<html>
<body>
<iframe id=”uploadFileFrameId” src=“javascript:false;” name=”uploadFileFrame”  height=”0″ width=”0″ frameborder=”0″ scrolling=”no”></iframe>
<form name=”uploadFile” enctype=”multipart/form-data” action=”/readFile.do” method=”POST” target=”uploadFileFrame” onsubmit=”validate();”>
<input type=”file” name=”filename” value=””/>
<input type=”submit” name=”submit” value=”upload file”/>
</form>
</body>
</html>

Invisible or Hidden iframe is used to upload a file to server. Thats the trick.! Lets explain each attribute of iframe & form tag to understand clearly.

iframe attributes

name – name of which uniquely identify the iframe. In our case its called “uploadFileFrame”
src – source file to show in iframe. In IE browser asks security popup msg when iframe src is empty, to solve this problem you can use javascript:false
height, width – define height & width of iframe, In our case it should not visible so we set value 0 for both.
frameborder – define to display iframe border, 0 – noborder
scrolling – define scroll bars. no – represent no scroll bar.

form attributes

name – define unique form name
target – where to open the file.
action – url to send data to server
enctype – define mime type. for file upload use multipart/form-data

In the above example, i used form attribute target equal to iframe name(target=”uploadFileFrame”) which means that iframe will take care of sending/uploading file to server when you submit a form.

New to Ajax, read below referred pages to learn basics.

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

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

Debugging Ajax with Firebug

October 21, 2008

Firebug is an addon of  Firefox browser. Its free and open source tool. This tool can help to debug script, ajax, edit html, css, dom in a live web page.
Firebug has an option to log the ajax requests & response. Suppose if you get any errors in ajax response you can easily identify using this tool. For instance, send an ajax request and get a response as XML. there has to be some issue in xml tags, throwing javascript error and failed to proceed further. Normally its hard to identify this issue. One way is to use javascript function alert to print the error but its cumbersome. But the Firebug tool will help you to troubleshoot the error easily & quickly.

Firebug tool enables you to see the request parameters send to the server.

For example, Form input parameters are not sending automatically to server when you submit a form through ajax. You have to manually collect and send to server. Using Firebug tool, you can see all the parameters and if it has any issues web developer can easily find it. One disadvantage is you can able to see the passwords parameter. To avoid this you must encrypt it before sending.

Firebug tool having the following features.

  • Firebug tool enables to view the web page load performance.
  • Easily find what are the images / js files are not loaded.
  • Easily edit the html, css without reload the page.
  • Execute javascripts in console.

You can get more details about firebug, visit here http://getfirebug.com/
Want to download the firebug use this link https://addons.mozilla.org/en-US/firefox/addon/1843

If you are new to Ajax, visit here to learn ajax basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

IE Browser failed to execute scripts in Ajax response

October 18, 2008

Send an ajax request to server and get an ajax response as html. The response has scripts at top of the page(assume its a jsp page). IE browser does not execute those scripts, just simply ignored it. When you access/called any script methods the browser will through script errors. Solution to solve this issue., move the scripts present in top of the jsp file to bottom area. Now the browser will execute the scripts and it works fine.

Web page will load faster when you place scripts in bottom of the file.

Reason is, browser will render a html tags easily and that should be displayed immediately. But evaluate the scripts will take some time and also required to send separate requests to server to load the specified script files.

Example.

test_not_working_ie.jsp

<html>
<script src=”/ajax.js” language=”javascript”></script>
<script src=”/ajaxform.js” language=”javascript”></script>
<script>
function validate()
{
var name = document.testform.name.value;
var age = document.testform.age.value;
if( name != null ){
alert(“enter valid name”);
return false;
}
if( age != null ){
alert(“enter valid age “);
return false;
}
sendAjaxRequest(“/testaction.do”, “showid”);
}
</script>

<body>
<table>
<form name=”testform” action=”testaction.do” onsumbit=”return validate();”>
<tr><td> Enter your name <input type=”text” name=”name”/></td></tr>
<tr><td> Enter your age <input type=”text” name=”age”/></td></tr>
<tr><td> <input type=”submit” name=”save”/></td></tr>
</form>
<div id=”showid”>
</div>
</table>
</body>
</html>

In the above file, scripts are written in top of the jsp file. Javascript validate method is called when you submit the above form, but that’s not happen in this case. Because those scripts are not loaded or executed when you render the page using Ajax. Lets see the simple solution below.

test_working_in_ie.jsp – scripts are moved to bottom of page

<html>
<body>
<table>
<form name=”testform” action=”testaction.do” onsumbit=”return validate();”>
<tr><td> Enter your name <input type=”text” name=”name”/></td></tr>
<tr><td> Enter your age <input type=”text” name=”age”/></td></tr>
<tr><td> <input type=”submit” name=”save”/></td></tr>
</form>
<div id=”showid”>
</div>
</table>
</body>
<script src=”/ajax.js” language=”javascript”></script>
<script src=”/ajaxform.js” language=”javascript”></script>
<script>
function validate()
{
var name = document.testform.name.value;
var age = document.testform.age.value;
if( name != null ){
alert(“enter valid name”);
return false;
}
if( age != null ){
alert(“enter valid age “);
return false;
}
sendAjaxRequest(“/testaction.do”, “showid”);
}
</script>

</html>

If you are new to Ajax see the below links to learn basics.

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/

NetBeans – 10th Birthday

October 17, 2008

NetBeans celebrates his 10th birthday on October(20-27) 2008. Since 1998, NetBeans has grown up well in open source projects from small to award winning project.
NetBeans is an open source Integrated Development Environment for software developers. Nowadays their having a lot of features and tools for creating web/enterprise applications.Also supporting the new technologies(Ajax, Ruby..,). I have been using this IDE for the past one year, really a nice one.!

For more details – http://www.netbeans.org/birthday

Ajax – Bookmarks & Browser History

October 16, 2008

Below are the two main drawbacks of the Ajax.

  • browser history is not added  – browser back button is not working when you rendered a web page using ajax. the reason, browser history is not updated while rendering a page using ajax
  • difficult to bookmark a page. – pages are rendered using javascript(ajax) , so not able to bookmark the page link.

How to solve this problem.?

We have to write a code to solve this problem. The main logic is LIFO(Last In First Out). Lets see how to implement that logic, write a javascript code to store the rendered page content into our own history stack and then shows the last stored page when browser back button is fired/triggered.

Also have another option., open source library to achieve the same. Simplest one is Really Simple History library. RSH is a lightweight javascript library for managing browser back & bookmarking in Ajax applications.

How RSH works.?

For IE browsers, hidden iframe used to trigger history changes
For other browsers, regular interval checks of location changes.

RSH will support IE, Firefox & Opera browsers.

For more details about RSH, please visit this link http://code.google.com/p/reallysimplehistory

Want to learn Ajax Basics, visit this link https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

JSON Example

October 13, 2008

JSON is a subset of javascript. Its a lightweight for data representations. Lets see the example.

JSON response should be like this.

bookobj=
[
“book1”:{
“bookname”:”ajax”,
“price”:600,
“chapters”:{”chapter1″:”Ajax Basics”, “chapter2″:”Ajax Examples”, “chapter3″:”Using JSON in Ajax”},
“authors”:[“orielly”,”nicholas”]
},
“book2”:{
“bookname”:”json”,
“price”:800,
“chapters”:{”chapter1″:”JSON Basics”, “chapter2″:”JSON DataTypes”, “chapter3″:”JSON Examples”},
“authors”:[“orielly”,”douglas crockford”]
}
]

Code to retrieve the data from the above response.

bookobj.book1.bookname – return the value of bookname “ajax”
bookobj.book1.chapters.chapter1 – return value of chapter1 in book1 “Ajax Basics”
bookobj.book2.authors[1] – return the value of book2 author “douglas crockford”
bookobj.book2.price – this will return the price of book2. “800”

Example for execute the scripts in the JSON data.
<html>
<body>
<div id=”titleid” style=”display:none;”>Book Name</div>
<div id=”bookname”></div>
</body>
<script>
function showTitle()
{
document.getElementById(‘titleid’).style.display = ”;
}
function showData(param)
{
document.getElementById(‘bookname’).innerHTML = param;
}
</script>
</html>

JSON response.

obj=
{
“callmethod1″:”showTitle()”,
“callmethod2″:”showData(‘Ajax’)”
}

execute the scripts using javascript eval function.

eval(obj.callmethod1); – this will execute the javascript showTitle method.
eval(obj.callmethod2); – this will execute the javascript showData method.

Are you new to JSON, pls read this first https://manikandanmv.wordpress.com/2008/10/08/json-java-script-object-notation/

Ajax response – XML vs JSON

October 11, 2008

Ajax response data can be any format like HTML, XML, JSON.  Below are some comparisons of XML & JSON.

XML

  • XML parsing is generic.
  • XML is a markup language and has semantics.
  • XML is most easily readable format for humans.
  • Easily validate the data using schema.

JSON

  • JSON data is faster than XML over the Http.
  • Scripts for JSON data are simpler than XML.
  • For i18n,  JSON seems to be an easy one.
  • Its very hard to read humans.

To conclude, based on your requirements you can choose the format either XML or JSON.

If you are new to Ajax or JSON. Kindly read the below links for learning basics.

Ajax – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

JSON – https://manikandanmv.wordpress.com/2008/10/08/json-java-script-object-notation/

Find MySQL version

October 10, 2008

Below are the possible ways to determine the version of mysql server.

  • display the version details when connecting to mysql server.
  • use the version variable to get the information about mysql

mysql>show variables like ‘%version%’;

  • use the version function to get the version details.

mysql>select version();

  • you can also use status command to get the version details & other informations.

mysql>status;

Using JSON in Ajax

October 9, 2008

Send an Ajax request to server and get a server response as JSON formatted object. JSON is an alternative of XML format. Lets see the below code for retrieving the data from JSON formatted object.

Assume the response text should be like this.

{
“productname”:”Java”,
“productdesc”:”java/jsp editor”,
“productprice”:650,
“validity”:”1 Year”
}

Example:

function sendAjaxRequest(url, divid)
{

url = url + getNoCacheValue(url);
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) {
var prod = req.responseText;
// retrieve data from JSON formatted response text.
var prod_name = prod.productname;
var prod_desc= prod.productdesc;
var prod_price = prod.productprice;
var prod_val = prod.validity;
// write your code here to show the above retrieved values.
}
}
}

Suppose if you want to execute the scripts present in the response text, use the javascript eval function.

If  you are new to ajax, pls read this https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

Also want to know about JSON, go here to learn basics https://manikandanmv.wordpress.com/2008/10/08/json-java-script-object-notation/