I have the following Spring Controller
#Controller
#RequestMapping("/accreq")
with the following mapping
#RequestMapping(value = "/defRoles", method=RequestMethod.GET)
public #ResponseBody String loadDefaultRoles(
#RequestParam(value="idGroup", required=false) String groupID
throws ServletException{
I'm trying to call this method with the following jquery ajax
$.ajax({
type: 'GET',
url: '/accreq/defRoles',
data: {idGroup: $('#infoGroup').val() },
success: function() {
alert("success");
}
});
Please help me figure out why the Spring method is not being called even though the ajax method is being called when I click a button. I have stepped through the script with firebug and it definitely hits the ajax function.
First, try to see what happens if you hit the URL manually in the browser
If that is successful, turn on request tracking in firebug and see if firefox actually hits the URL (and what the response says)
try to add this to your jquery
error: function(jqXHR, textStatus, errorThrown) {
alert("error:" + textStatus + " exception:" + errorThrown);
}
}
and you will see if an error occurs
which pattern are you using in your web.xml? Search for the tag and see which pattern are you using.
For example, if you are using:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
you should use something like this:
$.ajax({
type: 'GET',
url: '/accreq/defRoles.html',
data: {idGroup: $('#infoGroup').val() },
success: function() {
alert("success");
}
});
Is it possible that there is a server side exception occurring and that is why you are not seeing a response. If you have debugging on make sure your exceptions are thrown and/or you have a log of the same.
Also your comment is kinda ambiguous what do u mean the spring methid is not being called even though the ajax methid is being called. Can you please clarify. Also waht would help is the firebug o/p of the call with a screenshot or seomthing.. also if firebug throws an error what error it is.
Related
I'm struggling with something.
i pass JSON data to my controller
$.ajax({
type:'POST',
url:'${pageContext.request.contextPath}/saveMovBienes2',
data: JSON.stringify({ dni:dni, table:table, tipoMov:tipoMov}),
dataType: "json",
contentType: 'application/json'
})
In my RestController, i handle this information like this
#PostMapping("/saveMovBienes2")
public String saveMovBienes2(#RequestBody Request myRequest)
saving the JSON elements into the object myRequest.
The thing is, having #RequestBody forces me to stay in that JSP, but i want to after processing this information, redirects to another page.
Tried with various ways to redirect but the view stays the same (in my console i see the info processing but the view is static)
I read people with the same problem, and their answer was "removing #RequestBody", but in my case i'm not able to make it work without the #RequestBody.
Is there any way to rediect? or i have to modify all my code?
I finnally find a workaround, thanks to the comments above:
.done(function() {
})
.fail(function(){
window.location = '${pageContext.request.contextPath}/nuevoMovimientoBU';
})
For some reason, its not entering to .done , but in .fail
While click on an add button i have given the jquery code to navigate next page.
Here is my jQuery code:
$("#id-add-mer").click(function(){
location.href="../ecom/addMer";
});
here is my controller:
#RequestMapping(value = "/addMer", method = RequestMethod.GET)
public String addMerchant() {
return "merchantRegistration";
}
here it redirects to that page, but i have 3 dynamically fetching dropdown inside this page. i'm trying to fetch the values by adding an onload event in the body tag. here is my ajax code
function loadDropDown(){
$.ajax({
type: 'POST',
url: "ecom/loadInd",
data: {},
dataType: "json",
success: function(data) {
count = Object.keys(data).length;
$("#id-industry").empty();
for(i=0;i<count;i++){
$("#id-industry").append('<option value="'+data[i].id+'">'+data[i].type+'</option>');
}
loadBank();
},
error: function(jqXHR, textStatus, errorThrown) {
alert("1Server Exception");
}
});
}
i'm making an ajax call to fetch 2nd dropdown at the success of 1st call. while loading this page as welcome file displays the fetched dropdowns, i'm using spring mvc and hibernate to retrieve the records. But here i'm getting the error. Can anyone tell me how can i fix this issue..Thanks in advance...
Its better if you can mention here, what you get as error message in your code. Otherwise try to follow below steps to identify the issue.
First of all you better check whether your http request can access your server. you can use third party tools as well as built-in element viewer for that.
if there is no issue with communication with controller then check the what will return from "/loadInd". Simply you can debug or you can use alert box to inside success block.
Happy Coding....
I am getting errors on callBacks. I have tried following code in jsfiddle.com . You can also try. Data from servelet is not returning. It's returning same error again and again. Check jquery library when you try in jsfiddle
$.ajax({
url : 'http://192.168.16.111:8081/MiddleWareUsman/androidServlet',
type : "post",
dataType: "jsonp",
data : {
"fname": "chaaaaapiio",
"lname": "gya"
},
success : function(data) {
alert("hello"+data);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
My server side:
String a=request.getParameter("fname");
String b=request.getParameter("lname");
response.getWriter().write(a+" "+ b);
It appears you have a couple problems.
JSONP requests can't be sent via POST. They are actually sent as <script> tag requests anyway which are GET requests.
Your server isn't doing JSONP. For the server to do JSONP, it must wrap the requested data in a call to a javascript function who's name was passed as an argument to the request and then the actual data is passed as an argument to that function. JSONP is a big hack, but it works by requesting a javascript and that's what the server must return.
you simply can't send a POST request using JSONP
check this link out to see how JSONP works..
I need to test the browser window width in JSP, to determine whether or not I have to set a value in the request object. Typically I would achieve this with something like this:
if(document.body.offsetWidth < xxxx){
// ...
}
But I don't know how to do it with a JSP expression.
You might misunderstand that jsp and javascript existed on same file. Yes but JSP part compiles on server side itself comes to client.
You can't do that with JSP.
JSP compiles on serverside Where as javascript plays on browser i.e on client side.
Do it with javascript.You should do it in document load
when you do if(document.body.offsetWidth < xxxx) you are doing it at client side. Now if you want to propagate some client side value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).
Here is the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
data: { windowWidth: "100"}
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
Trying to send a simple text from my rest service and read it using ajax call. Found many answers about jsonp and cross browser compatibility, tried crossdomain too.
Here is the rest service:
Trimmed everything down to send only a simple string.
#GET
#Path("/getcontents2")
#Produces({MediaType.TEXT_PLAIN})
public String getContents2(#QueryParam("name") String msg) {
return "abc";
}
The ajax call:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://metrics/getcontents2?name=Work/loc.txt',
crossDomain: true,
async: false,
dataType:'html',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
console.log(xhr);
},
});
});
The browsers opens up the string as is. I guess something is really wrong in the jquery script.
Error on Firebug:
GET http://metrics/getcontents2?name=Work/loc.txt 200 OK 4ms
0
(an empty string)
(an empty string)
Object { readyState=0, status=0, statusText="error"}
Fixed it!
It was because my server was not supporting cross-domain. Configured it will corsfilter and it worked like a charm!
try setting your datatype to text jsonp
dataType: 'jsonp',
http://api.jquery.com/jQuery.ajax/
You will have to do one of two things to go with this to resolve the error further;
making changes on the server side to pass the data back as json and not as text
retun the string encoded in json return "{"text":"abc"}"; //or something like this
Why?
jquery cross-domain requests are only allowed for dataTypes "script" and "jsonp".
I have updated your fiddle it still throws an error but that is related to a parse json error