I have a problem while returning jsp from controller using ajax+spring mvc. I want to refresh a piece of the full page. In fact this is display-tag table. My controller send me this page, but the data that back to me from a controller is a jstl tags it is not html page. So browser, certainly, do not show me that page.
$(document).ready(function() {
alert("asdfads");
//$('#content').load('<c:url value="/pages/new.jsp"/>');
$.ajax({
url : '/shop/getCartProducts/ajax/',
type : 'GET',
async: false,
data : {},
success : function(data) {
$('#content').html(data);
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " : " + textStatus + " : " + errorThrown);
}
});
});
My Controller Looks like this
#RequestMapping(value = "/getCartProducts/ajax/", method = RequestMethod.GET)
String ajaxGetProdCart(HttpServletRequest request, Model model) {
LOG.error("We are in the controller");
PaginatedListImpl<Product> paginatedList = new PaginatedListImpl<Product>(request);
productService.getProductsFromCart(paginatedList, null, 100);
model.addAttribute("paginatedList", paginatedList);
return "cartProduct";
}
cartProduct.jsp
<display:table class="table" id="product" name="paginatedList" defaultsort="1" requestURI="/shop/cart/" excludedParams="*" export="false">
<display:column>
<a href='<c:url value="/cart/remove/"/>'> <img
src='<c:url value = "/resources/images/forbidden.png"/>'>
</a>
</display:column>
<display:column sortable="false" sortProperty="name" title="Product"
maxLength="55">
<c:url var="prodUrl" value="/product/${product.product_id}/" />
<a href='<c:out value="${prodUrl}"/>'> <c:out
value="${product.name}" />
</a>
</display:column>
<display:column property="price" paramId="price" sortable="false"
title="Price" href="#" />
<display:column property="descr" sortable="true" paramName="descr"
title="Description" maxLength="250" sortName="descr" /></display:table>
Alert show me this code it not show me html.
If what you showed us is the full code of the JSP, then you simply forgot to declare the two taglibs at the top of the JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="display" uri="http://displaytag.sf.net" %>
Related
I'm using Spring to get json data, and then i want to display data on HTML page.
This is my class:
#RequestMapping(value = "/selectCountNotification.do")
public ResponseEntity<List<EgovMap>> selectCountNotification(#RequestParam Map<String, Object> params, ModelMap model) throws Exception {
System.out.println("########################################");
System.out.println("####################check log####################");
System.out.println("########################################");
List<EgovMap> countNotification = orderDetailService.selectCountNotification(params);
model.addAttribute("countNotification", countNotification);
return ResponseEntity.ok(countNotification);
}
This is my header.jsp
<li>
<div class="notification" style="top: -5px;left: -40px;height: 36px;">
<i class='far fa-bell' style='font-size:20px'>
<div id="not">
<%# include file="/WEB-INF/jsp/sales/order/countNotify.jsp"%>
</div>
</i>
</div>
</li>
this is my countNotify.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>data: </p>
<c:forEach items="${countNotification}" var="comm">
<p><c:out value="${comm.countNotify}"/></p>
</c:forEach>
when i call by url:
http://localhost:8080/sales/order/selectCountNotification.do
I get data value from my database following as:
12
but when i run my jsp is countNotify.jsp, it cannot get any value, So how i can fix the problem ?
I am trying to upload a photo and get a preview of the uploaded image using Spring and Ajax.
I have the following code:
<h3>File Upload</h3>
<ul>
<li>
<form id="upload-form" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="uploadfile" size="45" accept="*" />
<br>
<input id="submit-button" type="submit" value="Upload" />
</form>
</li>
<li><p>Result: <br><span id="result"></span></p></li>
</ul>
<h3>Show Image</h3>
<ui>
<li>original:<img id="image-o" src="#" alt="original image" /></li>
<li>small: <img id="image-s" src="#" alt="small image" /></li>
<li>medium: <img id="image-m" src="#" alt="medium image" /></li>
<li>large: <img id="image-l" src="#" alt="large image" /></li>
<li>extra large: <img id="image-xl" src="#" alt="extra large image" /></li>
</ui>
<script type="text/javascript">
$(document).ready(function () {
$("#submit-button").on("click", function (event) {
event.preventDefault();
// create an FormData object
var data = new FormData($('#upload-form')[0]);
// disabled the submit button
$("#submit-button").prop("disabled", true);
// post data
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "image/api/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
// shows server's response
// $("#result").text(data);
console.log("SUCCESS: ", data);
enableSubmitButton();
updateImages(data);
},
error: function (e) {
// shows server's response
// $("#result").text(e.responseText);
console.log("ERROR: ", e);
enableSubmitButton();
updateImages(e.responseText);
}
});
});
});
function enableSubmitButton() {
$("#submit-button").prop("disabled", false);
}
function updateImages(data) {
var url = 'http://localhost:9001/image/api/' + data;
$('#image-s').attr('src',url + '?size=s');
$('#image-m').attr('src',url + '?size=m');
$('#image-l').attr('src',url + '?size=l');
$('#image-xl').attr('src',url + '?size=xl');
$('#image-o').attr('src',url + '?size=o');
}
</script>
And my Java code:
#POST
#Path("/upload")
#Consumes(ExtendedMediaType.MULTIPART_FORM_DATA)
#Produces(ExtendedMediaType.APPLICATION_JSON_UTF8)
#Transactional
public ResponseEntity<Void> uploadImage(#RequestParam("uploadfile") MultipartFile file) {
if (file.getSize() < maxFileSize && validExtensions.contains(file.getContentType())) {
Image image = Image.builder().id(file.getSize()).build();
imageServiceConfigMapper.saveImage(image);
/* FormDataContentDisposition fileDetail = null;
ImageMetadata imageMetadata = buildImageMetadata(fileDetail, image);
imageServiceConfigMapper.saveMetadata(imageMetadata);*/
}
return new ResponseEntity<>(HttpStatus.OK);
When I choose a photo from my PC, it is accepted - see screenshot below:
When I click in upload, my browser gives the following answer:
The JSON looks like this:
BUT the selected picture is not showing:
Am I using a wrong URL?
The address of the site where I got the above screen ends is the one with index.html at the end, but I defined /api/upload as a relative path...
If I open the relative path, I got the following:
Or is it something wrong with the code responsible for the preview?
Sorry, I know there is a tones of similar issues but I could not found anything that hepled. I am quite a beginner...
Sorry for the long post and thanks for the help in advance!
Spring Content can do this and has a getting started guide and git repo with an angularjs based front-end that demonstrates exactly what you are trying to do. The getting started guide is here.
I have a grid(html-table) with a lot of columns and want to combine filtering and sorting on this table.
At the moment I only use filtering on one column but sorting on several columns.
I want to do this with ajax.
I read an article [http://www.craigburke.com/2011/01/23/grails-ajax-list-with-paging-sorting-and-filtering.html]
and tried to adapt it to my version of grails-3.2.6.
This has been very hard to solve and now I'm totally stuck.
If I add something in the filter nothing happens but when I click on a column, the filtering takes place and also sorting, clicking a second time, ajax is not called and the filter is overwritten with the default value. I have managed to implement it on a test project which act the same.
It is much code and maybe there is a way to include the whole project in this question in some way?
I'll try to show most of the important part here if it could help.
The index.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'person.label', default: 'Person')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>
<script type="text/javascript">
$(document).ready(function() {
setupGridAjax();
setupFilterAjax();
});
</script>
<script type="text/javascript">
function setupGridAjax() {
$('#gridPersons').find('.paginateButtons a, th.sortable a').on('click', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var grid = $(this).parents("table.ajax");
$(grid).html($("#spinner").html());
$.ajax({
type: 'GET',
url: url,
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
})
});
}
</script>
<script type="text/javascript">
// Turn any input changes or form submission within a filter div into an ajax call
function setupFilterAjax(){
alert('FILTER--Anropat');
$('div.filters select:input').on('change',function(event) {
var filterBox = $(this).parents("div.filters");
filterGrid(filterBox);
});
$("div.filters form").submit(function() {
var filterBox = $(this).parents("div.filters");
alert('FILTERBOX - '+filterBox);
filterGrid(filterBox);
return false;
});
}
// Reload grid based on selections from the filter
function filterGrid(filterBox) {
alert('FILTER-change detected');
var grid = $(filterBox).next("div.gridPersons");
$(grid).html($("#spinner").html());
var form = $(filterBox).find("form");
var url = $(form).attr("action");
var data = $(form).serialize();
alert('FILTERGRID - '+url);
$.ajax({
type: 'POST',
url: '${g.createLink( controller:'person', action:'index' )}',
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
});
}
</script>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="list-person" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<div class="filters">
<g:form action="register">
<div id="selectMill">
Select tags:
<g:select class="selected" name="tag" from="${tagList}" value="${filters?.tag}" noSelection = "${['':'All']}" optionValue="" optionKey="" />
</div>
<div id="gridPersons">
<g:render template="Grid_Persons" model="personList" />
</div>
<div class="pagination">
<g:paginate total="${personCount ?: 0}" />
</div>
<fieldset class="buttons">
<input class="save" type="submit" value="${message(code: 'offer.create.from.buffer.label', default: 'Create')}" />
</fieldset>
</g:form>
</div>
</div>
</body>
The template: _Grid_Persons.gsp
<table class="ajax">
<thead>
<tr>
<g:sortableColumn property='reg' title='Register' />
<g:sortableColumn property="id" title='Id' params="${filters}"/>
<g:sortableColumn property='name' title='Name' params="${filters}"/>
<g:sortableColumn property='tag' title='Tag' params="${filters}"/>
<g:sortableColumn property='registered' title='Registered' params="${filters}"/>
</thead>
<tbody>
<g:each in="${personList}" status="i" var="ps">
<tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
<td><g:checkBox name="ckb" value="${ps.id}" checked="false" /></td>
<td><g:link action="edit" id="${ps.id}">${ps.id}</g:link></td>
<td>${ps.name}</td>
<td>${ps.tag}</td>
<td>${ps.registered}</td>
<td>
</g:each>
</tbody>
The index-part of the controller:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def tagList = Person.withCriteria {
projections {
distinct("tag")
}
}
def List<Person> personList = getPersonList()
// Paging def prodBuffer = getPaginatedList(prodBuffer, max, params.offset?.toInteger())
def filters = [tag: params.tag, sort: params.sort, order: params.order]
def model = [personList: personList, filters:filters, tagList:tagList]
if (request.xhr) {
println("AJAX-Request!!!")
render(template:"Grid_Persons", model:model)
prodBuffer, offerDetails:offerDetails, filters:filters])
} else {
offerDetails: offerDetails, millList: millList, selectedMill:false, prodBufferCount: ProdBuffer.count()]
[personList:personList,tagList:tagList]
}
Person.count(), tagList:tagList]
}
def List<Person> getPersonList() {
println("getPersonList tag: "+params.tag)
def tag = params.tag
def c = Person.createCriteria()
def tempList = c.list {
if (tag) eq("tag", tag)
if (params.sort){
order(params.sort, params.order)
}
}
return tempList
}
From debugging:
The page is loaded:
getPersonList tag: null
Selected "Grails" in the filter:
getPersonList tag: Grails
AJAX-Request!!!
Klicked on the "Name"-column header
getPersonList tag: Grails
AJAX-Request!!!
-- Now the list is sorted(ascending) and filtered
Klicked on the column again:
getPersonList tag: Grails
-- Now the list is resorted(descending) and the filtering still ok but the SELECT TAGS now view "All"
Klicked the column for the third time:
getPersonList tag:
AJAX-Request!!!
-- Now the list show all lines and resorted(ascending)
Now solved by using the recommended plugin - datatables.
In case you are in a hurry you can inject https://datatables.net/ that adds the utilities you require among others
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head cache="true" />
<script>
myfunction(a, b)
{
if ( a> b)
return true;
else
return false;
}
</script>
</head>
....
<s:form action="saveXXXX" >
.... fields....
<s:submit onclick="return myfunction(a, b);" /> //THIS ONE WORKS - NON AJAX
<sx:submit onclick="return myfunction(a, b);" /> //Using sx ajax tag
<sj:submit onclick="return myfunction(a, b);" id="formSubmit1" targets="formResult" value="AJAX Submit" button="true" /> //if using Jquery Plugin ajax tag
//how to stop form submittal if function returns false.
</s:form>
The form works using s:submit .. but now that I'm trying to ajaxfy it with sx:submit ... or jquery's sj:submit ...
I want to submit the form CONDITIONALLY using AJAX based on what the function returns.
How can it be done?
Instead of using submit button use a simple button
<s:form action="saveXXXX" name="myForm">
<input type="button" onclick="myfunction(a, b);"/>
</s:form>
and in your function
function myfunction(a, b){
if ( a> b)
document.myForm.submit();
}
Have you tried with the ' onsubmit="return myFunction();" ' attribuite within the tag?
<s:form action="actionName" onsubmit="return myFunction();">
...
</s:form>
I have a scrollable GridView in my Web Part and I have to make an AJAX call on each user scroll. I use Jquery 1.7.1 in the web part to call a c# handler class.
I am getting error 500 : Internal Server Error.
Here is a sample of the ascx :
<div id="divProducts" style="height:300px;overflow:auto">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" EnableViewState="false">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle CssClass="header" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
</asp:GridView>
</div>
<div id="divProgress" style="margin-top: -50px;margin-left:150px;z-index:-999">
<asp:Image ID="image1" ImageUrl="~/_layouts/images/MyWebPart/loading.gif" width="100" height="100" runat="server" />
</div>
<script type="text/javascript">
$(document).ready(function () {
//initially hide the loading gif
$("#divProgress").hide();
//Attach function to the scroll event of the div
$("#divProducts").scroll(function () {
//User has scrolled to the end of the grid. Load new data..
$("#divProgress").ajaxStart(function () {
$(this).show();
});
$("#divProgress").ajaxStop(function () {
$(this).hide();
});
BindNewData();
});
});
function BindNewData() {
$.ajax({
type: "GET",
url: "/_layouts/MyWebPart/FetchRecordsHandler.ashx",
success: function (data) {
alert('data ', data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
I added a ASHX file that will be deployed in Layouts folder of my web part project (Layouts/MyWebPart/FetchRecordsHandler.ashx) :
<%# WebHandler Language="C#" Class="MyWebPart.Code.FetchRecordsHandler" CodeBehind="FetchRecordsHandler.cs" %>
And I created the class FetchRecordsHandler that implements IHttpHandler with correct namespace :
namespace MyWebPart.Code
{
class FetchRecordsHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Write("From the handler at " + DateTime.Now);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
This method doesn't work in my web part. Any idea of a solution or maybe another technic to make ajax calls from the scroll events to the web part ?
Thx
You need to change your .ashx to something like:
<%# WebHandler Language="C#" Class="MyWebPart.Code.FetchRecordsHandler, {my assembly}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx" %>
Where {my assembly} is the name of the compiled .dll (without the .dll), probably MyWebPart and xxxxxxxxxxxxxxxx is the public key token for your assembly. One way to find this would be to look at the deployed .ascx from your web part, the first line or so should contain something similar.
I imagine the 500 error you are receiving has something to do with the fact that SharePoint cannot load the assembly for your .ashx. You could look in the event viewer for more details.