Archive for the ‘AJAX’ Category

How to open Ajax Page in Browser New Tab

May 18, 2009

It’s not easy task to support both “Load a web page using Ajax” and “Allow to open the same page in browser new tab”. Because we have to manually handle the second option. Let’s see how to solve this task.
Before proceeding, first you have to know why ajax web pages are not able to support the second option.
Reason : when you click a web page link, it will just invoke a javascript method specified in onclick event which loads the page through ajax requests. So here “href” attribute of anchor tag is either empty or “javascript:void(0);”. Due to this we are not able to open the page in new tab.

Sample code for achieving both the actions

  • ajax page load
  • the same page should be able to open in Browser New Tab by using “Open Link in New Tab” option.

Two operations handled in the web page links(anchor tags),

  • invoke the method showPage when u click the link. which means simply onclick event gets fired.
  • if u open the same link in new tab, the below sequence of actions will execute.
    • # part of href(say, #/blogs/JSON/json-basics.html) has appended to the browser url
    • showtab method has invoked beco’z the main page gets loaded. rest will take care of the method showtab

main page should be like this.

<html>
<body>
<a href="#/blogs/JSON/json-basics.html" onclick="showPage('/<span style="color:#000000;">blogs</span><span style="color:#000000;">/JSON/json-basics.html');">JSON Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html');">Ajax Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html');">HTML Basics</a></span>

<span style="color:#000000;">
<div id="showhelp"></div>
<!-- This div is the Common Dynamic Area, this area gets changed based on clicking the above link --></span>

<script>
showtab();
/* this method gets executed everytime when a page loads.
what this method does,
just get the full url from the browser address bar.
parse the url and get the exact "new page url" which is available after the symbol "#"
and send the "new page url" via ajax request.
*/

function showtab()
{
var url = document.location.href;
var index = url.indexOf("#");
var taburl = "";
if(index>0){
var taburl = url.substring(index+1);
}
sendAjaxRequest(taburl, "showhelp");
}

function showPage(url)
{
sendAjaxRequest(url,"showhelp");
}

function sendAjaxRequest(url, divid)
{
var req = <a href="https://manikandanmv.wordpress.com/2008/09/29/ajax-example">getXMLHttpRequest</a>();
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;
}
}
}

</script>
</body>
</html>

Are you new to Ajax..? Read the below posts for learning 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/

Advertisements

Ajax Search

November 14, 2008

With Ajax you can able to dynamically showing the searching results for a search item. Instead of entering a search value in the text box and submit the value after that get a search results in a list. Its an old model. Now web technologies are growing rapidly. So we move to the current trend is an important one. In Ajax Search, the implementation should be like this; type a character sequence in the text box during that time we will query the database for that search value and retrieve & showing the matching results dynamically. The below example will explain you clearly.

Example.

Database Name : Books
Table Name : BookDetails

BookId BookName Author Price
1001 Ajax Nicolas Zakas 1000
1002 Java Herbert Schildt 800
1003 JSP & Servlet James Gosling 1200
1004 C Programming Dennis Ritchie 300
1005 C++ Programming Bjarne Stroustroup 600
1006 Operating Donald 750

Action Class : BookDetails.java

File contains search logic to retrieve data from the database and send results to the client in XML format.

import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BookDetails extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Details of DB
String driverName="org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost:2345/Books";
String username="root";
String password="";
Connection con=null;
try
{
Class.forName(driverName);
con = DriverManager.getConnection(url,username,password);
}
catch( SQLException e )
{
e.printStackTrace();
}
Statement stmt = conn.createStatement();;
ResultSet res = null;
String input = request.getParameter("searchtext");
res = stmt.executeQuery("select BookName from BookDetails where BookName like '%"+input+"%'");
Sting output = "";
String result = "";
while( res.next() )
{
String bookname = res.getString("BookName ");
result = ""+bookname+"";
}
output = output + result + "";
System.out.println("Search Output is : "+output);
stmt.close();
conn.close();
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.println(output);
out.close();
}
}

Client File : book.jsp

File used to get the input of search value and shows the matching search results.

<html>
<script src=”ajax.js” language=”javascript”></script>
<script src=”ajaxsearch.js” language=”javascript”></script>
<body>
<form action=”BookDetails” name=”book”>
Enter Search value : <input type=”text” name=”searchtext” value=”” onkeyup=”showSearchItems(this.value)”/>
</form>
<div id=”showdetails”>
</div>
</body>
<script>
function showSearchItems(val)
{
sendAjaxSearchRequest(“\BookDetails”, “showdetails”);
}
</script>
</html>

Script File : ajaxsearch.js

function sendAjaxSearchRequest(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) {
var response = req.responseXML;
var tags = response.getElementsByTagName(BookDetails)[0];
var result = “”;
for(i=0; i<tags.length; i++)
{
var bookdet = tags[i];
var bookname = bookdet.childNodes[0].firstChild.data
result += “<div>”+bookname+”</div>”;
}
document.getElementById(divid).innerHTML = result;
}
}
}

onkeyup – is one of the property of  html tags. method specified in this property gets fired when you type any characters in the search input box. In our example javascript method showSearchItems called and this should produce the search results for your entered search input.

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/

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/

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/

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/

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/