0

I am having terrible nightmares with ajax and javascript... i'm trying to read the JSON answer and redirect to other site.

My Javascript is supposed to query the verify servlet waiting for procedure == login || loginAlreadyInUse and then redirect it to other place:

<script type="text/javascript">
var userId = "<%=request.getSession().getId()%>";
var timeInterval=self.setInterval("check_userId()", 3000);

function check_userId() {
$.post('http://localhost:8080/qrlogin/verify', {userId: userId}, 
    function(data) {
       if(data.procedure == "login") {
             window.location = 'http://localhost:8080/qrlogin/login'+userId;
        }
       else if(data.procedure == 'loginAlreadyInUse') {
            window.location = 'http://localhost:8080/qrlogin/'+userId;
         }
     }, "json");

}

The verify servlet at the moment:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/javascript");
    PrintWriter out = response.getWriter();
    // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
    out.print("{'procedure' : 'login' }");
    out.flush();
    return;
}

The problem is the script never redirects to the login page. (keep making the post every 3 secs...)

thanks for your time,

Winter
  • 1,896
  • 4
  • 32
  • 41

1 Answers1

4
  1. "{'procedure' : 'login' }" is not valid JSON. All keys and strings in JSON must be double-quoted, not single quoted. So you need to out.print() this instead:
    "{\"procedure\" : \"login\" }"

  2. text/javascript is the wrong MIME type for JSON. Use application/json.

  3. Don't pass strings to setInterval (or setTimeout, for that matter). It's eval in disguise, which we all know is evil (right? right?). Just pass the function itself:

    var timeInterval=self.setInterval(check_userId, 3000); // look ma, no quotes
    
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710