Here is a JSON formatter on the lines of Javascript formatter. Sometimes these prove to be useful to understand badly formatted useful code.
Thursday, May 01, 2008
Saturday, August 04, 2007
AJAX response: HTML, XML, JSON
Its fun to have the partially refreshing dynamically modifiable page using AJAX, both for application developer and for application user. But as a application developer parsing the partial response from server and dynamically modifying the DOM can become very complicated, parsing the response itself can be very tedious. Though the 'X' in AJAX stands for XML but your response need not be XML, it could be any text format, for our discussion we consider following three text response types
- HTML/plaintext
- XML
- JSON
var expandAreaDiv= document.getElementById("expandAreaDiv");
expandAreaDiv.innerHTML=text;
But life is not this simple always :-). As you application matures need arise to modify multiple section of the page with one response. One response and multiple modification means you can no longer use the response as is, you have to parse the response. By default we tend to use XML as the only option; after all 'X' in AJAX stands for XML :-)Take a simple example, if you performed update of some entity using AJAX than probably you need to do following
if successSo bare minimum you need three separate informations from server in one response
update the status field
show the success message
else
show the failure message
boolean value indicating success/failure
String value containing the message response
String value containing the new Status
So you decide to have XML like this
<myResponse>
<isSuccess></isSuccess>
<newStatus></newStatus>
<message></message>
<myResponse>
and in javascript you parse the response to get values into variables and then use it..
and as your XML becomes complex parsing becomes more complex and you start looking for some parsing tools. This is where i like JSON, which stands for JavaScript Object Notation. Your JSON response would look like this:var response= req.responseXML.getElementsByTagName('myResponse');
var isSuccess = getNodeValue(response,'isSuccess');
var newStatus= getNodeValue(response,'newStatus');
var message= getNodeValue(response,'message');function getNodeValue(obj,tag){
return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}
{
"isSuccess" = true,
"message" = "Successfully updated the Status",
"newStatus = "Active"
}
and here is you response parsing code in JS:var response = eval( '('+req.responseText + ')' );
and voila you can acess response.isSuccess, response.newStatus, response.newStatus. All parsing is done for you just by eval().
Be careful that you take care of JSON special character " and control characters like CR NL in the generated response.
e.g.
"message" = "Successfully
updated the Status",
will not work. JSON is not as readable as XML, but its more readable for computer :-) . Though I could not find any powerful JSON editor but this one is useful.Finally, as far as security is concerned JSON by itself is just a data format (like XML) so it is secure, but the eval function is not, so if someone could inject malicious script into your JSON, that would get executed on to the client. So make sure you validate the data before you put into JSON response (this you should do anyway if you need your application to be secure).
Friday, August 03, 2007
html checkbox submitting unchecked value
If you have used checkbox you would know that the checkbox value get submitted with form only if checkbox is checked, this is required by w3 html spec . What if you want to know if a checkbox was already checked when page was rendered and now unchecked by user. Specially if you are using a framework like struts and want to set a value in ActionForm based on checkbox value. Try submitting the form using Java script
<form name=myForm action="something.do" >
<input type=checkbox name=mycheckbox value=test />
...
Your normal form code here
...
<div id="hiddenArea"/>
<input type=button name='submitMyForm' value='submitMyForm' onclick='submitMyForm()'>
</form>
function submitMyForm(){
var hiddenArea = document.getElementById("hiddenArea");
var myCbx = document.myForm.mycheckbox;
if(!mCbx.checked){
var hiddenStr = "<input type=hidden name=mycheckbox value=notest />";
hiddenArea.innerHTML =hiddenStr;
}
document.myForm.submit;
}
Sunday, July 29, 2007
Printing session attributes and request attributes in JSP for debugging
I generally like to use following JSP which I call req_session_attribute_printer.jsp for debugging purpose. I just include this jsp, where ever i want to debug, i have found this very useful over time for simple debugging.
<%--
req_session_attribute_printer.jsp
Author:<a href="mailto:get.anurag at gmail do com">Anurag Kumar Jain</a>
Date: July 25, 2007
--%>
<%@ page language="java" contentType="text/html; "%>
<script type="text/javascript">
function showHideAttributes(spanId){
if(document.getElementById(spanId).style.display=='block'){
document.getElementById(spanId).style.display='none';
}else if(document.getElementById(spanId).style.display=='none'){
document.getElementById(spanId).style.display='block';
}
}
</script>
<a href="#" onclick="showHideAttributes('debugSpan')"> Attributes</a>
<span id='debugSpan' style='display:none'>
Session Attributes:
<% java.util.Enumeration salist = session.getAttributeNames();
while(salist.hasMoreElements()){
String name=(String)salist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
Request Attributes:
<% java.util.Enumeration ralist = request.getAttributeNames();
while(ralist.hasMoreElements()){
String name=(String)ralist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
</span>
This is specially very helpful for debugging in environments other than dev, where you have less control.
IE Caching issue with AJAX HTTP GET request
There is one very annoying issue with IE using AJAX when you use a HTTP-GET request (I haven't faced this problem with HTTP-POST request). I tried following but nothing seemed to work:
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
So we need to fool IE to consider the request as new request everytime, and you can fool IE by adding current timestamp at the end of your url. You can do following in your Javascript code:
url= url+"?currDate="+ new Date(); if your url is simple like /test/something.do
OR
url= url+"&currDate="+ new Date(); if your url contains request parameters and looks something like /test/something.do?id=1234
Creating your own ajax loading image
I found this useful for creating images for my AJAX loading ICONs http://www.ajaxload.info/