jQuery Ajax POST call with JSON in Rest Web Service Issue - ajax

I want to post a JSON object from my page to a Rest WS. But when I am posting json through jQuery ajax call as output I am getting a HTML page with "HTTP Status 405 - Method Not Allowed" instate of JSON, which I am sending from Rest Web Service. Please refer the following code snippet.
I am using jquery 1.11.3 version.
http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
jQuery Ajax Call:
$.ajax({
url: "http://localhost:8080/MyWebService/api/myService/jsonpost",
method: "POST",
data: jsonObj,
dataType: 'application/json',
contentType: "application/json",
success: function(result){
alert(result);
},
error(){
console.log('Error');
}
});
Please note my rest web service is running in my local tomcat.
Please find my Rest Web Service POST code.
#POST
#Path("/jsonpost")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String crunchifyJsonPostREST(SampleVO input) throws JSONException{
SampleVO sampleVO = input;
return new Gson().toJson(sampleVO);
}
VO:
public class SampleVO {
private String name;
/**
* #return the name
*/
#XmlElement
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
My Maven Dependency is:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
Firebug Details:
Please find my ajax request Header.
Please find my ajax response and response HTML.
Need your help to resolve this issue.
Thanks is advance.
Solution:
After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet

After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet

datatype should be dataType: 'json'
If you are using contentType: "application/json", , then you should stringify your data.
data:JSON.stringify(jsonObj),

Try using type & contentType settings of ajax:
type:'POST',
contentType: 'application/json',
Example:
function loadDoc(){
var num = '{"empid": 45,"name": "gaurav","salary":566.55}';
$.ajax({
url: 'http://localhost:9029/addS',
method: 'POST',
type:'POST',
contentType: 'application/json',
success: function(response){
console.log("response::::"+response);
$("#output").text(response);
},
error: function( jqXHR,textStatus, errorThrown){
console.log("Error askdjk");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}

Related

Unable to get response from JAX-RS endpoint with ajax [duplicate]

While sending a post request from my tomcat web service i got an error as below:
" Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I'm using tomcat 9.* and developed my web service with jax-rs java web api.
While i have tested my web service with postman, i got a good response from my web service (http 200 response). Yet, when i tried to send ajax post request i got the message above. I tried to enable the CORS filter and tried to send get request that working fine..
the web.xml:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>'
the jax-rs post function:
#POST
#Path("/users2")
#Consumes("application/json")
#Produces(MediaType.APPLICATION_JSON)
public Response SetAllTlcsStatus(List<TrafficLight> c){
System.out.println("You have entered the SetTlc function");
return Response.ok() //200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE,
PUT")
.allow("OPTIONS").build();
}
the ajax request:
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'
You say "I tried to enable the CORS filter and tried to send get request that working fine."
Do you mean that GET method works but POST not? If so you must allow it on your REST service/terminal and also these settings
header("Access-Control-Allow-Origin", "*")
header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
Finally, if by any chance your AJAX still returns failed try
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
**xhrFields: {
withCredentials: true
},
crossDomain: true,**
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'

Servlet mapping issue with websphere

Following is my servlet mapping:
Path: EAR/WAR/WEB-INF/web.xml
<servlet>
<servlet-name>GetChartDetails</servlet-name>
<servlet-class>com.high.GetChartDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetChartDetails</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Following in the location of my JSP:
Path: war/Monitor/XYZ.jsp
Inside this jsp, I am trying to make ajax call by calling above servlet as follows:
$.ajax({
type: "GET",
url:"http://localhost:25014/Monitor/GetChartDetails? jsonp="+chartType,
dataType: 'jsonp',
jsonpCallback: chartType,
error: function () {
alert("Error is occured");
}
});
chartType is a string. I am getting the alert as "Error is occured" and servlet is not being called.
Can someone please help me with this. Thank you.

ajax cross domain failed to get response

I have two servers:
Server 1 (URL: https://server1.AAA.com) and
Server 2 (URL: https://server2.AAA.com)
In Server 1 JSP page, I try to use ajax to send a POST request to Server 2.
$.ajax({
type: "POST",
url: "https://server2.AAA.com/servlet",
data: 'test',
success: function(data, textSuccess) {
alert(data);
}
error: function(xhr, status, error) {
alert('error');
},
});
In Server 2, I checked that it has received the request from Server 1, and I tried to response the following message:
doPost(...) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.getwriter().write("success");
}
However, I found that Server 1 cannot receive the response data from Server 2, it went to the error alert. I have totally no idea why such a situation happened. I have already set response header for all origins, and did set the security constraint in my application's web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>test</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
Please tell me what I am still missing / what should I check.

Authentication headers are not sending JQuery Ajax

I have web server hosted in Apache Tomcat 7 with Basic authentication. I have Tomcat user 'tomcat' with role 'tomcat' and password 'tomcat'. Following are my web.xml file and script snippet in client side respectively.
Web.xml
<?xml version="1.0" encoding="ASCII"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>testservice</display-name>
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>testservice</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testservice</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>testservice</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
</auth-constraint>
<user-data-constraint>
<!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
Client script:
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
</script>
I'm pretty sure about that there's no problem with Web Service and Basic authentication. But from client script, no authentication headers are sending. I tried header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==") too. But request is sending without authentication headers. Any help will be appreciated.
Two things to try:
1) Add the CORS Filter to your Tomcat configuration
add the CORS Filter to your Tomcat configuration. Note Access-Control-Allow-Origins has been purposely left blank below, so no site has access via CORS. But the important parameter that is configured is Access-Control-Allow-Credentials.
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2) Modify Your Ajax Call
Modify your beforeSend in your ajax call like so:
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
Only other thing I noticed is that your web.xml might also need the following:
<security-role>
<role-name>tomcat</role-name>
</security-role>
Hope this helps.
Found that passing authentication via headers is not working with jQuery ajax with jsonp data type. So tried following and works fine.
$.ajax({
type: "GET",
url: "http://tomcat:tomcat#localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
function callbackMethod(data) {
alert(data);
}
mccannf got us 99% of the way there with a similar issue hover we switched up how we set the withCredentials property and this worked for us. notice we set the xhrFields property. This can been seen within the jQuery documentation for the ajax method here; http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
xhrFields: { withCredentials: true },
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
succes: function(res) {
alert(ers);
},
error: function(err) {
alert(err);
}
});
However, we were not using jsonp, simple json.
I haven't found a solution for this, only a workaround:
Send the Authorization header using two headers, the standard one and a custom one for IE:
beforeSend: function (jqXHR, settings) {
if (self._hasAuthInfo()) {
jqXHR.setRequestHeader("Authorization", self._makeAuthHeader());
jqXHR.setRequestHeader("IEAuth", self._makeAuthHeader());
}
}
The server side will check both (the second one only if IE and if the standard one is not present)

$.ajax DELETE ignoring data

I found this link when searching for a solution. It suggests a bugfix in version 1.4.x. Thats a realy old version and i havent been fixed yet?
$.ajax ignoring data param for DELETE requests
The code below works perfectly find on a GET taking exactly the same request parameters. How I call the DELETE method?
var data = {
accessToken : accessToken
}
$.ajax({
type : 'DELETE',
url : "/user/" + userId,
cache : false,
data : data,
success : function(profile) {
$("#account-delete .response-container").html(JSON.stringify(profile, null, 2));
$("#account-delete .request-container").html("/user/?" + $.param(data));
},
error : function(jqXHR, textStatus, errorThrown) {
$("#account-delete .error-container").html(textStatus +" - " + errorThrown);
}
});
you probably shouldn't be using DELETE because some browsers won't support it according to the jQuery documentation.
Maybe this answer will help as an alternative.
did you check out this other SO question Here? This may be your problem:
Just a note, if you're using an IIS webserver and the jquery PUT or DELETE requests are returning 404 errors, you will need to enable these verbs in IIS. I've found this to be a good resource:
http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx
Ok this soultion works.
Add this filter in web.xml
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
Call the controller with POST providing _method: 'DELETE' in data.
$.ajax({
url: "/application/form",
type: 'POST',
data: {
_method: 'DELETE',
param : "param"
},
success: function (res) {
console.log("success");
} ,
error: function (res) {
alert(res);
}
});

Resources