$.ajax DELETE ignoring data - ajax

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);
}
});

Related

Cannot connect to local Rest Service with AJAX (Status: 0)

I currently try to connect to a local Rest service with AJAX. However it seems as if I can't get any connection. The Rest Service runs under http://localhost:8080/LernApp/
For Testing I tried to connect to http://localhost:8080/LernApp/user/ which returns a JSON (GET).
I tested this link inside my Browser (works fine and displays the JSON) and with Postman (also works fine and gets the Answer with a status code of 200 (OK)).
However if I try to connect to it with AJAX, it fails (status code 0).
My first try was this:
var xhttp = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhttp.open('GET','http://localhost:8080/LernApp/user/',true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() {
var data;
if(xhttp.readyState==4) {
if(xhttp.status==200) {
alert("OK");
} else if(xhttp.status==404) {
alert("404");
} else {
alert("ERROR CODE: " + xhttp.status);
}
}
}
xhttp.send();
The next thing I tried was this:
$.ajax({
type: 'GET',
url: 'http://localhost:8080/LernApp/user/',
dataType: 'json',
async: true,
success: function(result) {
alert(result.message);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status + ' ' + jqXHR.responseText);
}
});
And the last thing I tried was this:
$.ajax({
type: "GET",
url: 'http://localhost:8080/LernApp/user/',
headers: {
Accept : "application/json"
}
})
.done(function (data, textStatus, jqXHR) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("STATUS: " + jqXHR.status);
});
None of these seem to work. Every function returns the status code 0.
Does anyone have any idea what is happening here? Like I've said: Browser and Postman can connect to the url without and problems and retrieve the correct data.
Thanks for your help.
I finally found the solution. I should have mentioned more about my server (but since the server did well in the Browser and in Postman, I assumed that the problem would be on the client side).
Well... it was of course a server problem. The server is running on Apache Tomcat 9 with an embedded H2 database and JAX-RS (for REST Service).
If anyone else faces my problem: the solution is called CORS. If you are having the same problem, first google CORS, so that you know what it is and then you can make all of the needed settings inside the web.xml and/or context.xml of your Tomcat Project.

ajax request adding url paratemeters

I'm unsure if I'm just thinking of this the wrong way of thinking or I'm just missing something.
I have a search box that does some wildcard searches in a database. I have made this an ajax request so I don't need to reload the page and I can have a little please wait icon while the data loads.
Now as there is pagination so I could do with the url parameters being added to the url, can you do this on a ajax request, ad if so how?
here is a sample code (param1) :
data : $('#form-contactSupplementaire').serialize() + "&param1=value",
Request full ajax :
$.ajax({
method : "POST",
url : "...",
data : $("...").serialize() + "&param1=value",
dataType: "",
success : function (json) {
// ...
console.log(json);
}, error: function () {
console.log("Error");
}
});

jQuery Ajax POST call with JSON in Rest Web Service Issue

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);
}
});
}

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.

Load a frame/iframe through spring mvc

I have a problem where when a user presses a submit button on the top of the page, another jsp is loaded in the frame/iframe below. I'm using the Spring MVC architecture and the jsp is decided by the controller. How should I make the controller map the jsp to the iframe? For all previous mappings I used #RequestMapping annotations.
I would do this using Javascript, for example with JQuery you can do an ajax call when the onSubmit even is called on your form to load the response (html content) in your iframe:
$('form').submit(function() {
jQuery.ajax({
type : 'POST',
data : jQuery(this).serialize(),
url : '/post_action',
success : function(data, textStatus) {
jQuery('#iframeId').contents().find('body').append('data');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
just use this thing --
$("#iFrameId").attr("src", "controller.mth");
this way the jsp returned from controller will be loaded in the iframe.
With Spring MVC, the ajax url worked after I used request.getContextPath in scriptlet.
My controller receives the request after this change and returns the jsp page. The jsp then display in an iframe after changing the append('data') to append(data) in example. Notice, removed quotes in data to make it work.
function openPage() {
jQuery.ajax({
type : 'POST',
data : jQuery(this).serialize(),
url : '<%=request.getContextPath()%>/post_action',
success : function(data, textStatus) {
jQuery('#iframeId').contents().find('body').append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

Resources