Archive for December, 2005

AJAX caching problem

Written by coregps on Thursday, December 1st, 2005 in Java, AJAX.

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

People all over the internet are talking about the hottest buzzword - AJAX (or Asynchronous JavaScript and XML). As we already know, it is not a technology in itself, but a term that refers to the use of a combination of technologies to create interactive web applications, including HTML (or XHTML) and CSS, DOM, the XMLHttpRequest object. Now we can see some excellent applications using AJAX such as Google Maps.

I also use it in my online exam project. The following are the code:

xmlhttp.js, which used to create the XMLHttpRequest Object

function getHTTPObject() {
      var xmlhttp;
      /*@cc_on @*/
      /*@if (@_jscript_version >= 5)
             try {
                 xmlhttp=new ActiveXObject(”Msxml2.XMLHTTP”)
             } catch (e) {
                 try {
                     xmlhttp=new ActiveXObject(”Microsoft.XMLHTTP”)
                 } catch (E) {
                     xmlhttp=false
                 }
           }
      @else
           xmlhttp=false
      @end @*/
      if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {
           try {
                xmlhttp = new XMLHttpRequest();
           } catch (e) {
                xmlhttp=false
           }
      }
      return xmlhttp;
}
var xmlhttp = getHTTPObject();

The function below communicate with JSP and return the result of the operation

function makePaper(planid, roomid) {
  var url = “makepaper.jsp?planid=” + planid + “&roomid=” + roomid;
  xmlhttp.open(”GET”, url, true);
  xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState == 4) {
    result = xmlhttp.responseText;
    if (result == ’success’) {
        alert(”Success!”);
    } else {
        alert(”Failed!”);
    }
   }
  }
  xmlhttp.send(null);
  return false;
}

The server side JSP is something like this:

<%@page pageEncoding=”UTF-8″ contentType=”text/html; charset=UTF-8″
%><jsp:useBean id=”makepaper” class=”com.esurfer.exam.MakePaper”/><%
String paperroomid = (String)request.getParameter(”roomid”);
String paperplanid = (String)request.getParameter(”planid”);
makepaper.setRoomid(paperroomid);
makepaper.setPlanid(paperplanid);
boolean b = makepaper.setPapers();
if (b) {%>success<%} else {%>false<%}%>

The code above works only the first time, from the second time on, the function return quickly without performing any operation. I had encounted the same issue before and I had solved it by adding an additional parameter currTime as follows:

var url = “answer.jsp?examid=” + examid + “&examanswer=” + thisvalue + “&currTime=<%=new java.util.Date()%>”;

This time I solve the problem by adding an additional parameter that use the javascript Date function. So, I can ensure that each time a new request is made.

function makePaper(planid, roomid) {
    var now = new Date();
    var url = “makepaper.jsp?planid=” + planid + “&roomid=” + roomid + “&time=” + now.getTime();
    xmlhttp.open(”GET”, url, true);
    xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
        result = xmlhttp.responseText;
        if (result == ’success’) {
            alert(”Success!”);
        } else {
            alert(”Failed!”);
        }
    }
  }
  xmlhttp.send(null);
  return false;
}

Ok, Below are some resources about AJAX:

Form post using Ajax

Written by coregps on Thursday, December 1st, 2005 in Java, AJAX.

Ajax becomes increasingly popular as a new approach to create rich client web applications. By using Ajax we can submit form data to web server in the background asynchronously. I’ve been using Ajax in many projects. Such as changing the content of select elements dynamically, creating auto-completion text field etc. However, I came across some trouble in my recent instant message system base-on Ajax. I want to send messages using Ajax when users press the ctrl and enter key. When I sent Chinese characters, I got ???. I tried to encode the message using encodeURIComponent(), as well as encode the entire URL using encodeURI, but no luck. Finally, I solved the problem by using post method and utf-8 encoding. The following code snippet is used to send messages:

<script type="text/javascript">
    function sendMessage() {
        var url = "send.jsp";
        var data = "sender=" + messageform.sender.value + "&receiver=" + messageform.receiver.value + "&message=" + messageform.message.value;
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xmlhttp.send(data);
    }
</script>

In the send.jsp page, we can retrieve the message from request parameter directly without setting the character encoding. It is something like this:

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"
%><%@page import="platform.*, java.util.*"
%><%
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "no-store");
String sender = request.getParameter("sender");
if (sender == null) sender = "";
String receiver = request.getParameter("receiver");
if (receiver == null) receiver = "";
String message = request.getParameter("message");
if (message == null) message = "";
// save message into database
%>

And the following are some excellent articles about submitting form using Ajax:

  • http://www.captain.at/howto-ajax-form-post-get.php
  • http://www.devarticles.com/c/a/XML/XML-in-the-Browser-Submitting-forms-using-AJAX/5/

There is also a new book - Ajax In Action which shows how to design Ajax apps and teaches numerous Ajax implementation techniques. You can visit manning’s site for more information.



Site Navigation