Search code examples
javajqueryajaxjax-rsjax-ws

Ajax and Java web service strange error


I got a really weird error. I successfully run my code and consume the web service. The service return 200 code. But jquery ajax executes error function instead of success. I post the information (Nothing on console):

Javascript:

$(document).ready(
    function () {
        $.ajax({
            url: 'Test/Service/hello',
            dataType: 'json',
            contentType: 'application/json',
            data: {name: 'testing'},
            error: function () {
                $('#text').html('<p>An error has occurred</p>');
            },
            success: function (data) {

                $("#text").html(data.d);
            },
            type: 'POST'
        });
    });

Java:

package com.morethansimplycode.webservice;

import javax.jws.WebParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/Service")
public class Service {

    public Service() {
    }

    @POST
    @Path("/hello")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces(MediaType.APPLICATION_JSON)
    public String hello(@WebParam(name = "name") String txt) {

        return "Hello " + txt + " !";
    }
}

Chrome info:

Remote Address:[::1]:8080
Request URL:http://localhost:8080/WebService/Test/Service/hello
Request Method:POST
Status Code:200 OK
Response Headers
view source
Content-Length:17
Content-Type:application/json
Date:Tue, 01 Dec 2015 21:24:26 GMT
Server:GlassFish Server Open Source Edition  4.1
X-Powered-By:Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  4.1  Java/Oracle Corporation/1.8)
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:es-ES,es;q=0.8,ca;q=0.6,en;q=0.4,pt;q=0.2,ru;q=0.2
Cache-Control:no-cache
Connection:keep-alive
Content-Length:9
Content-Type:application/json
Host:localhost:8080
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/WebService/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
name=paco

Preview:

Hello name=testing !

What's happening?

Edit 1:

Works with this call:

$(document).ready(
        function () {
            $.ajax({
                url: 'Test/Service/hello',
                dataType: 'text',
                contentType: 'application/json',
                data: {name: 'paco'},
                error: function () {
                    $('#etiqueta').html('An error has occurred');
                },
                success: function (data) {

                    console.debug(data);
                    $("#etiqueta").html('<p>' + data + '</p>');
                },
                type: 'POST'
            });
        }
);

But i don't know how can i send an object from the Web Service to the JS as Json to use it with data.d, etc...

Edit 2:

Working correctly as follows:

JS:

$(document).ready(
        function () {
            $.ajax({
                url: 'Test/Service/hello',
                dataType: 'json',
                contentType: 'application/json',
                data: {name: 'paco'},
                error: function () {
                    $('#etiqueta').html('An error has occurred');
                },
                success: function (data) {

                    console.debug(data);
                    $("#etiqueta").html('<p>' + data.d + '</p>');
                },
                type: 'POST'
            });
        }
);

Java:

@Path("/Service")
public class Service {

    public Service() {
    }

    /**
     * This is a sample web service operation
     *
     * @param txt
     * @return
     */
    @POST
    @Path("/hello")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces(MediaType.APPLICATION_JSON)
    public String hello(@WebParam(name = "name") String txt) {

        return "{\"d\": \"Hello " + txt + " !\"}";
    }
}

Solution

  • Instead of

    public String hello(@WebParam(name = "name") String txt) {
    
            return "Hello " + txt + " !";
        }
    

    try to use:

    public String hello(@WebParam(name = "name") String txt) {
    
            return "{\"d\" : \"Hello " + txt + " !\"}";
        }
    

    If you returns some complex class, for example Product, it's converted to json, but if you return String, lib can't convert it to {key=value} and think that you generated json manualy. See this question to more info.