SCV
SCV

Reputation: 416

ajax POST cannot send data to servelet

I am working on a simple tomcat web application. The client side just send the username data in json to server side and server side return if this username is already registered. Here is my code.

ajax part:

 var udata = new Array();
 udata.push({ name: uname});
 $.ajax({
    url: '/TestProj/Controller?action=checkuname',
    type: 'POST',
    dataType: 'json',
    data: udata,
    //contentType:'application/json, charset=utf-8',
    success: function(data){
        checkstatus = data.status;
    },
    error: function(x,y,z){ console.log(JSON.stringify(x)); }
});

servlet part: I am using a controller to dispatch the request to checkname servlet.

    String username = request.getParameter("name"); 

    if (checkuser(username)){
        status = "false";
    }else{
        status = "true";
    }
    response.setContentType("application/json");
    PrintWriter o = response.getWriter();
    o.println("{\"status\":\""+status+"\"}");
    //o.println("{\"status\":\""+username+"\"}");

I try print out the content of "status" and "username", but they are both null. Does it mean that I did not successfully send out the data via ajax to servlet. I may mess up the json data part. Any help will be appreciated.

Updated: I change the ajax part to this and it works. Can someone let me know how to do it in the json way?

ajax part:

 var udata = new Array();
 udata.push({ name: uname});
 $.ajax({
    url: '/TestProj/Controller?action=checkuname&uname='+uname,
    type: 'POST',
    dataType: 'json',
    data: udata,
    //contentType:'application/json, charset=utf-8',
    success: function(data){
        checkstatus = data.status;
    },
    error: function(x,y,z){ console.log(JSON.stringify(x)); }
});

Upvotes: 1

Views: 1044

Answers (1)

Tap
Tap

Reputation: 6522

It doesn't really make sense to use a JSON object for such a simple thing as posting a username to a servlet. Just use a simple request parameter and save yourself a lot of trouble. But if you must do it with JSON, there are a few problems you'll need to resolve.

  1. Unless you're handling multiple users at the same time, a javascript array is not a good choice of data type. A simple object would be better.

    var udata = {name: uname};
    
  2. Your post data should be a string, not a javascript object (array or otherwise). Use JSON.stringify() as in your error function.

    $.ajax({
        url: '/TestProj/Controller',
        type: 'POST',
        dataType: 'json',
        data: 'action=checkuname&jsonObject=' + JSON.stringify(udata),
        success: function(data){
            checkstatus = data.status;
        },
        error: function(x,y,z){ console.log(JSON.stringify(x)); }
    });
    

    However, udata is such a simple javascript object that you might as well stringify it yourself, as the native JSON object is not going to be available in older browsers.

    var udata = '{name:"'+uname+'"}';
    
    $.ajax({
        url: '/TestProj/Controller',
        type: 'POST',
        dataType: 'json',
        data: 'action=checkuname&jsonObject=' + uname,
        success: function(data){
            checkstatus = data.status;
        },
        error: function(x,y,z){ console.log(JSON.stringify(x)); }
    });
    

    Also, although it may boil down to personal preference, the action parameter is better off in the post body rather in the query string. This is a post, after all.

  3. request.getParameter() is not going to help you inspect a JSON string. It can only get the value of request parameters. So

    String json = request.getParameter("jsonObject")
    // this variable will have a value like "{name: 'somedude'}"
    

    You'll need to parse this JSON string on the server. You could try to do this yourself with String methods, by a library like Gson is a much better option. You could obtain the username value like this:

    String username = (String)(new Gson().fromJson(json, Map.class).get("name"));
    

Upvotes: 1

Related Questions