Not fetching dynamic dropdown using jquery spring mvc and hibernate - java

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....

Related

Redirect to another page with #RequestBody

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

JSP dynamic dependent select box

I am looking for a method to create a dynamic dependent select box in a JSP, preferably something AJAX/JQuery based so I don't have to make a separate trip to the server. I am updating an internal auditing page for my organization and adding a feature to allow for a 're-audit'. The first select box is populated on page load and is listing of all employees and the second, populated dynamically, should be a listing of the previous audits for the selected employee.
Try something like this in your javascript (do not forget to import latest stable version of jquery),
$(document).ready(function() { //This will be triggered on page ready
jQuery.ajax({
type: "POST", //Passing data in post method
url: "ServletURL", //Servlet URL
data: "userId=" + $("#userId").val(), //Post if you need to send anything
success: function (response) { //Ajax success data
alert("Details loaded successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) { //Ajax failure data
alert(xhr.status);
alert(thrownError);
}
});
});
And process the userId in servlet and transfer the resulted data into any jsp page, where you can convert your result into the type either json or xml for your comfort. This data will be returned as response in ajax success.

JSP - Testing document.body.offsetWidth

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

Jquery ajax call returns error when the rest service is returning a string

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

How do I call a Spring controller method with Jquery AJAX

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.

Categories