spring mvc return modelandview after ajax call - ajax

in my form I have table to show some of customer data.user can click on row to see all of customer data.
<div class="container">
<table class="table table-bordered" style="direction: rtl">
<thead>
<tr>
<th style="text-align: center">customer name</th>
<th style="text-align: center">customer ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer" varStatus="loop">
<tr onclick="retrieveCustomer('${loop.index}')">
<td id="id-${loop.index}">${customer.customerId}</td>
<td>${customer.customerName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function retrieveCustomer(id) {
debugger;
$.ajax({
url: "<%=request.getContextPath()%>/show_selected_customer",
data: {customerId: $('#id-' + id).text()},
type: "GET",
success: function (response) {
},
error: function (xhr, status, error) {
alert(error);
}
});
};
</script>
and in my controller:
#RequestMapping(value = "/show_selected_customer", method = RequestMethod.GET)
public ModelAndView showSelectedCustomer(#RequestParam("customerId") String customerId) {
Map<String, Object> model = new HashMap<>();
Customer customer = coreService.getCustomer(customerId);
model.put("customer", customer);
return new ModelAndView("showCustomerData", model);
}
tiles:
<definition name="showCustomerData" extends="base.definition">
<put-attribute name="title" value="customer data"/>
<put-attribute name="content" value="/WEB-INF/jsp/show_customer_data.jsp"/>
</definition>
until now every thing work correctly.
my problem is, it doesn't show show_customers.jsp page,and even I have no error in my log.
what is my problem,Is because of ajax call? I did`t use #responsebody and want to show customers.jsp page with return modelandview. thank you

Use the response body annotation and convert your entity to JSON and return it instead.

Related

Spring view page detail with ajax

I would like to know how you would make an ajax call to another page to show a listing containing the service data
Models.html
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Model</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Controller
#CrossOrigin
#GetMapping("/cars/{id}/model")
public List<Model> getModels(#PathVariable Long id) {
Optional<Car> car = carRepository.findById(id);
return car.get().getModels();
}
Json
$('table').on('click', 'button[id="model"]', function(e){
var id = $(this).closest('tr').children('td:first').text();
$.ajax({
type:"GET",
enctype: 'application/json',
url:"/cars/" + id + "/model",
success: function(data){
var models = JSON.parse(JSON.stringify(data));
for (var i in models) {
console.log(i);
}
},
error: function(err) {
console.log("Error");
}
});

BadRequest Error in ajax with Spring MVC

I am trying post a request to my controller and everytime when I hit submit button it gives an error of bad request.
I am not able to find out what is wrong with the code.
Home.jsp
<div id="setReminder">
<label class="generalReminder" style="text-decoration: none;">General
Reminder</label>
<table>
<tr>
<td>Date</td>
<td><input type="text" readonly="readonly"
id="birthdayDate"></td>
</tr>
<tr>
<td>Time</td>
<td><input type="text" readonly="readonly" id="callTime"
></td>
</tr>
<tr>
<td>Message</td>
<td><textarea id="reminderTag" rows="5"></textarea></td>
</tr>
</table>
</div>
<div id="reminderDot" style="margin-top: 24%; position: relative;">
<button class="submitReminder" onclick="saveReminderDetails();">Submit</button>
</div>
Home.js
function saveReminderDetails(){
var x="";
x=scheduleBirthdayReminder();
if(x){
$.ajax({
type:"POST",
url:"submitBirthdayRequest.do",
data : {
birthdayDate :$("#birthdayDate").val(),
birthdayTime : $("#callTime").val(),
birthdayReminder : $("#reminderTag").val()
},
success : function(data) {
alert('data is'+data);
$("#birthdayDate").val('');
$("#callTime").val('');
$("#reminderTag").val('');
}
});
}
}
Controller.java
#RequestMapping(value="submitBirthdayRequest.do",method=RequestMethod.POST)
public #ResponseBody String submitSchedulerDetails(#RequestParam("birthdayDate")String birthdayDate,#RequestParam("callTime")String birthdayTime,#RequestParam("reminderTag")String reminderTag,HttpServletRequest request ){
System.out.println("adding reminder details with birthdayDate "+birthdayDate+"and time"+birthdayTime);
String userIdentity=((UserDetails)request.getSession(false).getAttribute("loginDetails")).getName();
try{
boolean schedulerObj= schedulerService.addSchedulerBirthdayDetails(userIdentity,birthdayDate, birthdayTime,reminderTag);
}catch(Exception e){
e.printStackTrace();
}
return birthdayTime;
}
Error
http://localhost:8083/Testing/submitBirthdayRequest.do 400 (Bad Request)
the names of the parameters in the request don't match the expected. Try changing the
#RequestParam("birthdayTime") String birthdayTime
#RequestParam("birthdayReminder") String reminderTag
or change the param names on the client side

Ajax return form modelattribute

I have the following situation. In controller in method viewUserReminders I pass remindersListWrapper to my uReminder.jsp page.
#RequestMapping(value = "/user/reminders", method = RequestMethod.GET)
public ModelAndView viewUserReminders(Model model, #ModelAttribute("id_users") Long id_users) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/uReminders");
List<Reminders> remindersList=userService.getUserReminders(id_users);
RemindersListWrapper remindersListWrapper=new RemindersListWrapper();
remindersListWrapper.setRemindersList(remindersList);
mv.addObject("remindersListWrapper", remindersListWrapper);
return mv;
}
In my uReminders.jsp file I have a form with modelattribute remindersListWrapper. This jsp page displays table of reminders. Next to every reminder there is a checkbox. The user can check several checkboxes, click button("Mark as read") and using Ajax I submit form and go to controller method
readReminders().
uReminders.jsp
<form:form action="/user/ajax/reminders/readReminders" method="POST" modelAttribute="remindersListWrapper" id="remindersForm">
<div id="main">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th>Reminder</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<c:forEach items="${remindersListWrapper.remindersList}" varStatus="status" var="reminders">
<tr id="row">
<td><form:hidden path="remindersList[${status.index}].idCalendar"/></td>
<td><form:checkbox path="remindersList[${status.index}].isRead"/></td>
<td><form:input path="remindersList[${status.index}].endDate"/></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${empty remindersListWrapper.remindersList}">
<tr>
<td colspan="3">You have no reminders.</td>
</tr>
</c:when>
</c:choose>
</tbody>
</table>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<input type="button" id="reminders" value="Mark as read"/>
</c:when>
</c:choose>
</div>
</form:form>
$(window).load(function () {
$("#reminders").click(function () {
sendAjax('readReminders', $("#remindersForm").serialize());
});
});
In this method I save read reminders and I build newRemindersListWrapper with the new list of reminders(I want to delete checked reminders and display only unchecked). My first question is: How to return to the page newRemindersListWrapper itself.
#RequestMapping(value = "/user/ajax/reminders/readReminders", method = RequestMethod.POST)
#ResponseBody
public String readReminders(#ModelAttribute("remindersListWrapper") RemindersListWrapper remindersListWrapper, #ModelAttribute("id_users") Long id_users) throws Exception {
for(Reminders reminders:remindersListWrapper.getRemindersList()){
if(reminders.getIsRead()){
userDao.saveReadReminders(reminders);
}
}
RemindersListWrapper newRemindersListWrapper=new RemindersListWrapper();
///////////////////
here I want to return the newRemindersListWrapper itself
//////////////////
}
And my second question is: How I can set newRemindersListWrapper as modelattribute in my form.
function sendAjax(ref, data) {
console.log(data);
$.ajax({
url: 'ajax/reminders/' + ref,
type: 'POST',
data: data,
success: function (response) {
////////////////////////////////
I want to get newRemindersListWrapper and set it as modelattribute in form.
////////////////////////////////
console.log("success");
},
error: function (request, status, error) {
console.log('error ' + ref + ' text=' + request.responseText + ' status = ' + status + ' error = ' + error);
}
});
}
Question 1: just change the return type to RemindersListWrapper and return it
Question 2: Since you are using ajax, you can't. You need to use javascript to parse the returned list and update the page as needed.

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

web api though Method Not Allowed

i have got the bellow simple api
public class ProductRepository : IProductPrpository
{
#region IProductPrpository Members
public IEnumerable<Product> GetAll(string ProductOption)
{
return Utility.GetDiscountItems(ProductOption);
}
public Product GetProduct(string Id)
{
return Utility.GetProduct(Id);
}
public String PostBag(Bag bagofItem)
{
return Utility.PostBagDiscountedItem(bagofItem);
}
#endregion
}
it is working fine when i call GetProduct & GetProduct but when post for PostBag it through the Method Not Allowed -
http://localhost:54460/api/products?PostBag="
error
please help
there is my client side script which post data to PostBag Api
#model List<MultiBuy.Models.Product>
#{
ViewBag.Title = "Index";
}
<h2>Items in the bag</h2>
<table>
<tr>
<th> Item_number_option </th>
<th> Option_number </th>
<th> Price </th>
<th> PublicationCode </th>
<th> Quantity </th>
</tr>
#foreach (var item in Model)
{
<tr>
<td> #item.ItemNumber</td>
<td> #item.Option</td>
<td> #item.Price</td>
<td> #item.PublicationCode</td>
<td> #item.Quantity</td>
</tr>
}
</table>
<div>
<ul id="products" />
<input type="button" value="Search" onclick="find();" />
</div>
#section scripts {
<script>
function find() {
var dataJSON = '#Model';
$.ajax({
type: 'POST',
url: 'http://locallhost:54460/api/products?PostBag=',
data: JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}).done(function (data) {
$('#products').text(data)
});
};
</script>
}
appreciate all your help
You can not make a post in the same way you do the get, Get you can put parameters in your url, but Post you canĀ“t.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Resources