Fill in Bootstrap table after Ajax request (JSP and Spring MVC) - java

Hi I try to fill in my tables in my JSP view after having send a variable into an Ajax function.
<script type="text/javascript">
function filterByDate() {
var count = 680;
$.ajax({
url : 'filterOnDate',
data : {
"count" : count
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//alert(data); //here you will see an alert displaying the callback result coming from your spring controller
console.log("Request succeeded!");
console.log(data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
This Ajax request is send to a UserController who receive this variable and send it to the Model for performing an Hibernate search criteria in database.
#RequestMapping(value = "/eblinb2b/filterOnDate", method = RequestMethod.GET)
public #ResponseBody List<EblInvB2B> filterByDate(Model model, #RequestParam("count") int count) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_filter_counting = accountSservice.findByDateRangeEB2B(count);
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_filter_counting", eblinb2b_filter_counting);
return eblinb2b_filter_counting;
}
I already checked if the hibernate query retrieve the information from the COLUMN table after I put a Debug breakpoint i see my List with objects.
This is the DAO method with Hibernate criteria:
#SuppressWarnings("unchecked")
#Override
public List<EblInvB2B> findDateRange(int count) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("count", count));
return (List<EblInvB2B>) criteria.list();
}
What i'd like to do is to fill my table with a response to my Ajax only with the rows where i applied the criteria which is count that comes from my Ajax request it is equal to 680 it is an integer and should fill in my jsp table with only one row.
Just for information: I have a Different JSP view where I have and Update Button for populating mySql database it is in fact a batch that unmarshall XML files and put them into database. This is the usercontroller method :
#RequestMapping(value = "/eblinb2b/OutInCompare", method = RequestMethod.GET)
public String eblinb2bOutInCompare(Model model) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_list = accountSservice.findAllEblInvB2B();
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_list", eblinb2b_list);
return "eblinb2bCompare";
}
Here i want to display in my view the list passed by my Controller method onto my JSP view. I don't know if it is correct? : BOOTSTRAP PAGE
https://jsfiddle.net/eaL38ejr/
Thanks to all for your help!

You should've load the bootstrap table again after getting data from ajax.
<script type="text/javascript">
function filterByDate() {
var count = 680;
$.ajax({
url : 'filterOnDate',
type: 'GET',
dataType:'json',
data : {
"count" : count
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//alert(data); //here you will see an alert displaying the callback result coming from your spring controller
console.log("Request succeeded!");
console.log(data);
$('#tableID').bootstrapTable('load', data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
Or do a refresh,
$('#tableID').bootstrapTable('refresh', {
url: 'filterOnDate?count='+count
});
Edit
Ajax 406 indicates your request is not acceptable, hence you need to update your controller method like below.
#RequestMapping(value = "/eblinb2b/OutInCompare", method = RequestMethod.GET,
headers="Accept=*/*",produces = "application/json")
public #ResponseBody List<EblInvB2B> filterByDate(Model model, #RequestParam("count") int count) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_filter_counting = accountSservice.findByDateRangeEB2B(count);
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_filter_counting", eblinb2b_filter_counting);
return eblinb2b_filter_counting;
}
As well include type and dataType parameter's in your ajax request. Let me know if it helps.

Related

Form binding back with List of multiple select options

I'am trying to bind model in spring form multiple select using Select2 jquery library
but selected options are always null,
first i display form correctly with the available options, then user can update (add or remove) other choice which i fetch them remotely with an ajax request.
i am using next dto to bind form data :
DTO :
#Setter
#Getter
public class MyDto{
private List<Contact> agences;
private Contact banque;
spring mvc form to display avaliable user option :
...
<form:select path="agences" items="${MyDto.agences}" itemValue="id" itemLabel="name" />
...
select2 initialization to format and fetch additional options with an ajax request
Select 2 :
$("#agences").select2({
language: "fr",
multiple: true,
width: '100%',
ajax: {
url: "/fetchData.html",
method: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term,
banque : $("#IdBanque").val()
};
},
processResults: function (data, params) {
return {
results: $.map(data, function (item) {
return {
"id" : item.id,
"text" : item.name,
}
})
};
}
}
});
Controllor
#RequestMapping(method = RequestMethod.POST, value = "/update")
#ResponseBody
public ResponseEntity<?> updateIntranet(#ModelAttribute(value = "myDto") myDto, BindingResult result, HttpServletRequest zRequest) throws JSONException {
....
the problem is when i receive the request i can't find selected options and the List is null
how i can binding back the dto which include list of element using spring mvc

How to redirect to another request mapping of a spring MVC controller from a jsp within a jsp

Situation:
I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.
Sample controller:
#RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
System.out.println("In controller");
return "redirect:/anotherJSP";
}
#RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
System.out.println("In another");
return "anotherJSP";
}
Jsp within a jsp:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
},
error : function() {
alert("Error.");
}
});
Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!
You can't redirect a POST.
When you return redirect:/anotherJSP, the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.
The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.
Change #RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to #GetMapping("/anotherJSP") (assuming Spring 4.3 or later).
Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
window.location.href = /anotherJSP;
},
error : function() {
alert("Error.");
}
});

How To Call Spring MVC Controller From JQuery Ajax Call

i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.
First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.
Javascript function:
function authenticatePricingCalcLogin() {
var login = {
userName : $("#username").val(),
password : $("#password").val()
};
$.ajax({type: "POST",
url: CONTEXT_PATH+"authenticateLogin",
data:JSON.stringify(login),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success: function (response) {
if (response != null) {
if (response.errorMsg != null && response.errorMsg != "") { // Login Error
alert(response.errorMsg);
} else {
// Here i need to call spring controller method and to redirect to another page
// I have tried
$.ajax({type: "GET",
url: CONTEXT_PATH+"navigateMainPage",
data:JSON.stringify(loginDO),
contentType : 'application/json; charset=utf-8',
dataType : 'json'
});
}
}
}
});
}
AuthController.java
#RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public #ResponseBody LoginDO authenticateLogin(#RequestBody Login login){
return authService.authenticateLogin(loginDO);
}
#RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(#ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
try {
// Need to set User Name in session variable
} catch (Exception e) {
}
return "auth/mainPage";
}
Please add / in your path
url: CONTEXT_PATH+"/authenticateLogin",
Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side #ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.

Can I get a POJO in an Ajax Request to a Spring Controller?

I have a simple JSP file with some radios, one text input and one button.
In the button onClick I am doing an Ajax request to a Spring controller as you can see bellow:
function callFiltrarViaAJAX() {
var filtro = $("#filtro").val();
var optFiltro = $('input[name=optFiltro]:checked').val();
$.ajax({
type : "GET",
url : "filtrar",
//dataType : "json",
data : {
filtro : filtro,
optFiltro : optFiltro
},
success: function(data) {
console.log("SUCCESS: ", data);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
In the Spring controller I am receiving this request with success with the following code:
#Controller
public class FiltroController {
#RequestMapping(value = "/filtrar", method = RequestMethod.GET)
public #ResponseBody String filtrarVacina(FiltroTO filtro, HttpServletResponse response, ModelAndView model) {
VacinaTO v = new VacinaTO();
v.setId(new Long(10));
v.setLote("Lote 1");
v.setNome("BCG");
model.addObject("vacina", v);
response.setStatus(200);
return "TEST OK";
}
}
As you can see in the code above, I'm adding a POJO object in the ModelAndView that I'am trying to use in the JSP to show the return of the Ajax request in a table.
My Ajax request returns with success too but the problem is that even returning with success I can't use the POJO object, when I try to access the object by expression language I got nothing.
I've been searching about this situation and I found a lot of contents but none of the solutions that I've found works for me, but I found an interesting answer:
JSP inside ListItems onclick
So, is it means that I can't get a new parameter in the same JSP file with a Ajax request ? If yes, would be a JSON file the better way to get the return from the Spring controller ?
You can't access the model because you're returning an arbitrary string from controller instead of the view in which you want to access model.
If you're trying to access vacine from some.jsp, then you should return some from the controller method.
Of course, what I said is valid if you have proper ViewResolver configuration.

Spring MVC #ModelAttribute Not Binding Form

I am trying to POST to a Spring MVC controller method via ajax. Using Chrome's developer tools, I can tell that the values from the form are being sent, but in the method, the form values are null.
Here is the jquery call:
var form = $('#renegotiationForm').serialize();
$.ajax({
method:'POST',
url:'/renegotiate/wizard/startRenegotiation',
data:{'renegotiationForm': form},
success: function(data) { this.transitionTo(data); }
});
Here is the Spring MVC method (meant to return only a single string):
#RequestMapping(value="wizard/startRenegotiation", method = RequestMethod.POST)
public #ResponseBody String processStart(#ModelAttribute("renegotiationForm") RenegotiationForm form, BindingResult bindingResult) {
log.debug("Entered showStart(), method=POST");
RenegotiationType type = RenegotiationType.valueOf(form.getRenoType().trim().toUpperCase());
RenegotiationActivity activity = RenegotiationActivity.valueOf(form.getRenoActivity().trim().toUpperCase());
String result = "";
if (type == RenegotiationType.TYPE1 && activity == RenegotiationActivity.ACTIVITY1) {
result = "deleteType1";
}
return result;
}
The values are bound using the Spring Form taglib, and I have confirmed that the path attributes of the form tags match the fields of the RenegotiationForm.
I think it's because you are trying to send an "string" from ajax and you want to get and Object (RenegotiationForm), try to change it to String and Format in Server-side. I recommend you to add the type you are sending from client-side, too.
#RequestMapping(value = "wizard/startRenegotiation", method = RequestMethod.POST, produces="application/json")
Found the answer. Further on in my code, I had a function like this:
var ajaxcall = function() { $.ajax({
// ajax settings
});
}
Unfortunately, setting it up this way doesn't make it work as a jquery deferred, and specifically I couldn't use the .then() function to process of ajax requests.
Thanks for the help.

Categories

Resources