sahiljain
sahiljain

Reputation: 2374

Calling Restful Web service using jQuery ajax doesnt work

I am using restful web service and trying to query it from jquery ajax call RESTAPI

@GET
@Path("/dynamicReports")
@Produces("application/json")
public String getDynamicFilters() {
           String JsonStr=null;
    JSONObject json=new JSONObject();
    JSONObject tempjson=new JSONObject();
    tempjson.put("number", 200);
    json.put("response", tempjson);
    JsonStr=json.toString();
    System.out.println("inputJson : "+JsonStr);
        Response.ok().header("Access-Control-Allow-Origin", "*").build();
    return JsonStr;
}

My jquery ajax call

 $.ajax({
        type: "GET",
        dataType:"jsonp",
            crossDomain: true,
        url:  "http://url:port/DynamicReportsService/dynamicReports",
        success: function(data1) {
            console.log("response:" + data1);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $("#loadingimageid").remove();
            alert('generateReportFromMR:Error in processing!');
            console.log(jqXHR);
        }
    });

In browser if i try the url it gives me {"response":{"number":200}}. but ajax call gives an error and in web console it shows the json with error.

Upvotes: 0

Views: 2969

Answers (1)

NEO
NEO

Reputation: 2001

When you use jsonp you need to use the callback parameter which the browser sends to give the response. Setting the dataType to jsonp will allow jQuery to automatically add an extra ?callback=? to the end of your URL to specify the callback.

Basically the call expects the result to be of jsonp format but you only return json format. By enclosing your json inside the callback parameter you ensure that jsonp is returned and not json.

When you check the console, the GET request will be contain something like

?callback=jQuery152035532653917078266_4305276802416

Now all you need to do is use 'jQuery152035532653917078266_4305276802416' and you should give a response like,

jQuery152035532653917078266_4305276802416({"response":{"number":200}});

So in Java, you can use request.getParameter("callback") and then use that to return a jsonp.

return request.getParameter("callback") + "(" + jsonStr + ");";

If you want to use custom callback then your ajax request should be like,

$.ajax({
        type: "GET",
        dataType:"jsonp",
            crossDomain: true,
        url:  "http://url:port/DynamicReportsService/dynamicReports",
        jsonpCallback: 'successCallback',
        success: function(data1) {
            console.log("response:" + data1);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $("#loadingimageid").remove();
            alert('generateReportFromMR:Error in processing!');
            console.log(jqXHR);
        }
    });

And response be,

return "successCallback(" + jsonStr + ");";

Upvotes: 1

Related Questions