partial tiles loading on ajax success in Spring tiles - ajax

I have a base tiles definition as:
<definition name="base_layout" template="/jsp/tools_tiles_layout.jsp">
<put-attribute name="body1" value="" />
<put-attribute name="body2" value="" />
</definition>
One page is defined as:
<definition name="tool_Home" extends="base_layout">
<put-attribute name="body1" value="/jsp/default/tool_body/list1.jsp" />
<put-attribute name="body2" value="/jsp/default/tool_body/list2.jsp" />
</definition>
Now one of my controller method load this page like:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String getListsById(Model model, String Id) {
List<String> list1 = null;
List<String> list2 = null;
try {
list1 = getList1FromDB();
list2 = getList2FromDB();
}
model.addAttribute("list1", list1);
model.addAttribute("list2", list2);
} catch (PersistenceException e) {
logger.error("error in ",e);
}
return "tool_Home";
}
Now i want to load only list2.jsp after a ajax call
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("Accept", "text/html;type=ajax");
},
type : 'POST',
url : "./add?fragments=body2",
data : formData,
cache: false,
contentType: false,
processData: false,
datatype : "json",
beforeSend: function(req) {
req.setRequestHeader("Accept", "text/html;type=ajax");
},
complete : function(jqXHR)
{
$("#body2").html(jqXHR.responseText);
}
});
And my controller method for this Ajax Call is
______________________________________________
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, HttpServletRequest request) {
try {
List<String> list2 = getList2FromDB();
} catch (PersistenceException e) {
logger.error(e.getMessage(), e);
}
model.addAttribute("list2", list2);
return "tool_Home";
}
Here is my bean definition
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions" ref="TilesList"/>
</bean>
<bean id="TilesList" parent="parentTilesList">
<property name="sourceList">
<list merge="true">
<value>/WEB-INF/tiles.xml</value>
<value>/WEB-INF/tool-tiles.xml</value>
</list>
</property>
</bean>
But the partial loading is not working? what i am doing wrong?

Related

spring mvc Ajax

I want to run Ajax and showResults. I have created simple 2 JSP pages,1 CONTROLLER and 1 DOMAIN.I am using netbeans.I am unable to add users and see all user list.
AddUser. jsp
<script type="text/javascript">
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" >
function doAjaxPost() {
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "url",
data: "name=" + name + "&education=" + education,
success: function (response) {
$('#info').jsp(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<c:url var="user" value="/ShowUsers"/>
<form:form method="POST" modelAttribute="user" action="${user}">
<table>
<tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
<tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
<tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
</table>
Show All Users
</form:form>`
ShowUsers.jsp
<table>
<tr>
<td>Name</td>
<td>${user.name}</td>
</tr>
<tr>
<td></td>
<td>${user.education}</td>
</tr>
</table>
web.xml
<servlet>
<servlet-name>UserListController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UserListController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
UserListController-servlet.xml
<context:component-scan base-package="com.tutorialspoints" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
User.java
public class User {
private String name;
private String education;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
UserListController.xml
#Controller
public class UserListController {
private final List<User> userList = new ArrayList<User>();
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showForm(Model m) {
m.addAttribute("user", new User());
return "AddUser";
}
#RequestMapping(value = "/AddUser", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user, BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are " + userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "/ShowUsers", method = RequestMethod.POST)
public String showUsers(#ModelAttribute User user, ModelMap model) {
model.addAttribute("name", user.getName());
model.addAttribute("education", user.getEducation());
return "ShowUsers";
}
}
ShowUsers.jsp
<body>
<table>
<tr>
<td>Name</td>
<td>${user.name}</td>
</tr>
<tr>
<td></td>
<td>${user.education}</td>
</tr>
</table>
</body>
Pass you data as a simple json data: {'name': name, 'education': education}.
Change your ajax request as below
You were specifying them in query param string format which is wrong
"name=" + name + "&education=" + education
Correct your url that you are passing to the server. It should end with xyzabc/AddUser
$.ajax({
type: "POST",
url: YOUR_ACTUAL_SERVER_URL,
data: {'name': name, 'education', education},
success: function (response) {
$('#info').jsp(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('Error: ' + e);
}
});

Internal Server Error on ajax GET request in Spring MVC

Hi everyone i'm new to spring MVC so i have little idea about the framework. All I'm trying to do is refresh a div in my view with items filtered by a hibernate query, which prints correctly to standard out.
For some reason I'm not aware of I get a 500; Internal server error when i try a get request via ajax.
I changed the return type in the controller, my original idea was to use the default index controller with an optional parameter.
View:
<div id="itemListContainer">
<c:if test="${!empty items}">
<c:forEach items="${items}" var="item">
<c:url value="/showImage.htm" var="url">
<c:param name="id" value="${item.id}" />
</c:url>
<div id="${item.id}" class="col-lg-2 col-md-3 col-xs-6 thumb">
<img class="img-responsive" src="${url}" alt="${item.name}">
</div>
<input id="name_${item.id}" type="hidden" value="${item.name}">
<input id="name_${item.id}" type="hidden" value="${item.review}">
</c:forEach>
</c:if>
<c:if test="${!empty itemList}">
<h1>Nothing found</h1>
</c:if>
</div>
JS File
function filterItems(value) {
$("#itemListContainer").empty();
$.ajax({
method: "GET",
//dataType: "json",
url: "filterItems.htm",
data: {
type: value
},
success: function (data) {
if (data) {
$("#itemListContainer").html(data);
} else {
console.log(xhr.responseText);
alert("failure");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
Controller:
#RequestMapping(value = "/filterItems", method = RequestMethod.GET)
public #ResponseBody List<Item> filterItems(#RequestParam(value = "type", required = false) String type) {
List<Item> items = new ArrayList<Item>();
try {
items = itemDao.getItems(type);
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
Any help will be greatly appreciated. Thanks in advance!!
Once again, when it comes my little experience with hibernate, the error has nothing to do with Javascript, controller o DAO but with entity mapping.
My Item entity had an association with a User entity, and had to specify between lazy and eager loading of the association. In my case it was solved by adding lazy="true" to my xml file.

How to delete multiple rows of database using ajax and spring mvc

I want to delete multiples rows using ajax and spring mvc but it always delete just one row.
//code controller
#RequestMapping(value = "/rmvclientserviceajax", method = RequestMethod.POST)
#ResponseBody
public void rmvclintServiceajax (HttpServletRequest request, Model model)
{
for(String serviceID: request.getParameterValues("idService"))
{ Long clientID = (long) Integer.parseInt(request.getParameter("idClient"));
metiersr.deleteClientToService(clientID,(long) Integer.parseInt(serviceID));}
}
//code js
function AjaxPostdelete() {
if ($('#idService').prop('checked')) {
var idService = $('#idService').val();
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : "idClient=" + idClient + "&idService=" + idService,
success : function(response) {
{
{
}
}
// code html
<form>
<ul class="liste_servch">
<input type="hidden" id="idClient" value="${client.idPersonne}" />
<c:forEach items="${listservclt}" var="servclt">
<li>
<input id="idService" type="checkbox" value="${servclt.idService}" />
<c:out value="${servclt.nomService}" />
</li>
</c:forEach>
</ul>
<input type="button" value="supp" onclick="AjaxPostdelete() ">
</form>
Try following;)
function AjaxPostdelete() {
var idServiceObjs = $('input[id=idService]');
var idServices = [];
for (var i = 0; i < idServiceObjs.length; i++) {
if(idServiceObjs[i].prop('checked')) {
idServices.push(idServiceObjs[i].value);
}
}
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : {idClient:idClient,idService:idServices},
success : function(response) {
}
}
}

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource asp.net

I am facing problem with Cross Domain Ajax call. When I call a asp.net WebMethod through Ajax Call I got warning : Reason: CORS preflight channel did not succeed
Here is complete code
Server Code :
using System;
using Customers.BLL;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public partial class API_Default : System.Web.UI.Page
{
static string ApplicationPath = "";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ValidateUser(string UserName)
{
string strJson = "";
var User = Members.GetCustMaster(UserName);
if (User != null)
{
User.BankName = ApplicationPath + (User.BankName.ToString() != "" ? "Images/Photos/" + User.BankName : "images/avatar.png");
strJson = JsonConvert.SerializeObject(User);
}
else
{
JavaScriptSerializer json = new JavaScriptSerializer();
Failure failure = new Failure();
strJson = json.Serialize(failure);
}
return strJson;
}
}
[Serializable]
public class Failure
{
public bool Status { get { return false; } }
public string Result { get { return "Record Not found"; } }
}
I have added Headers in Web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
Thisis how I am trying to call this webmethod
<head>
<title></title>
<script src="jquery-1.11.1.min.js"></script>
<script >function GetJSon() {
var obj = {};
obj.UserName = $("#txt").val();
$.ajax({
type: "POST",
url: "http://someurl.net/webservices/default.aspx/ValidateUser",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
data: JSON.stringify(obj),
success: function (msg) {
console.log();
alert(msg.d)
$("#test").html(msg.d)
},
error: function () {
console.log();
}
});
}</script>
</head>
<body>
<input type="text" value="demo" id="txt" />
<input type="button" onclick="GetJSon()" value="jSon" />
Response : <div id="test">
</div>
</body>
</html>
Response for preflight has invalid HTTP status code 404

Ajax each function response is blank

I am doing search a product example using spring and ajax.I try to display the result using each function in a table. But getting blank response with headings being displayed. On firebug response field shows [].
Controller
#RequestMapping(value="searchproduct", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody List<Product> searchProduct(#RequestBody #RequestParam(required=false, defaultValue="productName") String productName,
Map model) {
List<Product> productResults = productService.searchProductByName(productName);
return productResults;
}
DAOImpl
public List<Product> searchProductByName(String productName) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Product.class);
criteria.add(Restrictions.ilike("productName", "%"+productName+"%"));
return criteria.list();
}
ServiceImpl
#Transactional
public List<Product> searchProductByName(String productName) {
return productDAO.searchProductByName(productName);
}
JSP
<script type="text/javascript">
$(document).ready(function() {
$('#searchForm').submit(function(event) {
var productName = $('#productName').val();
var json = { "productName" : productName };
$.ajax({
url: $("#searchForm").attr( "action"),
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(productResults) {
$('#searchTable').
append("<thead><tr><th>Product Name</th><th>Price</th></tr></thead>");
$('#searchTable').append("<tbody>");
var tableContent = "";
$(productResults).each(function(index, product){
tableContent +=
'<tr><td> ' +
product.productName+' </td><td> ' +
product.price+' </td></tr>';
});
$('#searchTable').append(tableContent);
$('#searchTable').append("</tbody>");
}
});
event.preventDefault();
});
});
</script>
<form id="searchForm" action="searchproduct.json" >
Product Name: <input type="text" name="productName" value="${product.productName}"
id="productName" />
<input type="submit" value="Search" />
</form>
<div id="formResponse">
<table id="searchTable">
</table>
</div>

Resources