Goal
After a POST request, I want to update a list. For example, if a user is added, so user list must be refresh.
So I do the post request, then I do a get request to update the content.
There is a way to do it without reload the page?
Thanks for your answer!
Ajax calls
function rafraichirContenu(url, type) {
$.ajax({
url: url,
type: type
}).done(function (response) {
$(document).html(response)
});
}
postRequest().done(function(response) {
rafraichirContenu('/emprunts/encours', 'GET');
...
});
Get Mapping
#GetMapping(value = "/encours")
public ModelAndView findAllEnCours() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("emprunts", empruntResource.getEmpruntsByStatutEquals(StatutEmprunt.EN_COURS));
modelAndView.setViewName("webapp/pages/emprunts");
return modelAndView;
}
HTML
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
Console error
jquery.min.js:2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of null
Related
This is my controller class read data method. I cant read spring data from requesting. when I do it from postman it works fine but cant read using html page.
#RequestMapping("/index")
public String ItemList(Model model) {
model.addAttribute("itemList", repository.findAll());
return "index";
}
Like this I try to read data using my index.html page
<h2>Medicine List</h2>
<form action="/index" method="POST">
<table>
<thead>
<tr>
<th>ID</th>
<th>MedicineName</th>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>ExDate</th>
</tr>
</thead>
<tbody>
<tr th:each="item:${itemList}">
<td th:text="${item.id}"></td>
<td th:text="${item.MedicineName}"></td>
<td th:text="${item.Description}"></td>
<td th:text="${item.Quantity}"></td>
<td th:text="${item.Price}"></td>
<td th:text="${item.ExDate}"></td>
<td><form action="/delete/item:${itemList}" method="Delete"><input type="submit" value="Delete" /></form></td>
</tr>
</tbody>
</table>
</form>
I'm trying to automatically update view (here list named emprunts) after insert into my database. I use Springboot, H2, JPA, Thymeleaf, ...
There is a way to do it? Or have I to refresh the page with Get request after the insert ?
Thanks a lot!
HTML / View
...
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
...
Controller
#PostMapping
public ResponseEntity<?> newEmprunt(HttpEntity<String> infoEmprunt) throws IOException {
...
repository.save(object);
return new ResponseEntity<>(HttpStatus.CREATED);
}
If your view technology is thymeleaf then return html page instead of returning ResponseEntity(because response entity will return data in json format) and add data in model attribute.
There is a way to do it? Or have I to refresh the page with Get request after the insert ?
No need to refresh page just return html page from controller like below.
Emprunt emprunt = repository.save(object);
model.addAttribute("emprunt", emprunt);
return "show"; //show.html page
I`m trying to send post request from JSP view to Controller by Button "onClick" method but i getting 404 Error that the RequestMapping is not sign, why is that?
HomeController:
#RequestMapping(value = "/showSelectedRequest/{id}", method = RequestMethod.POST)
public String loadRequestProducts(#PathVariable("id") int id, Model model) {
logger.debug("HomeController.RequestIdSelected() - Start");
logger.debug("HomeController.RequestIdSelected: id: " + id);
model.addAttribute("RequestIdSelected", id);
logger.debug("HomeController.RequestIdSelected() - Done");
return "/home";
}
Home.jsp:
<form action="${contextPath}/requestlist" method="post">
<table class="table table-sm">
<thead class="thead-inverse">
<tr>
<th>
Id
</th>
<th>
Name
</th>
<th>
Show request
</th>
</tr>
</thead>
<c:forEach items="${requestDTOList}" var="requestDTO">
<tr>
<td>
${requestDTO.getId()}
</td>
<td>
${requestDTO.getName()}
</td>
<td>
<button class="btn btn-info" onclick="post(/showSelectedRequest/${requestDTO.getId()})">Query</button>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</td>
</tr>
</c:forEach>
</table>
</form>
When you have a form, the action field is what will be executed when you will click on the input of type "submit".
As a solution you can modify your code as follow:
<form action="${contextPath}/showSelectedRequest/${requestDTO.getId()}" method="post">
// Form elements ...
<input type="submit" value="Query" />
</form>
I have tried to send a parameter from this thymleaf page
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${p}" th:method="post" th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${p.email})}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
and then I tried to receive the parameter (email) using this code
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#PathVariable("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The problem is when the value of p.email is something like myemail#gmail.com
what I receive in the method makeAndSendInvoice is only myemail#gmail
and it does not send me the .com part
How can I fix it?
(email=${p.email}) means , you are passing a query parameter.
So, how can you be able to catch the query param value using path variable?
We can use #RequestParam to catch the queryparam value in Spring
Try the below java code :
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#RequestParam("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The period in ".com" will need to be encoded to be used in the url to prevent it being parsed as the suffix
Your HTML:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form method="post" th:action="#{/dashboard/makeAndSendInvoice/__${p.email}__} ">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
Your controller
#RequestMapping(value = "/dashboard")
#Controller
public class testController {
...
#RequestMapping(value = "/makeAndSendInvoice/{email}", method = RequestMethod.POST)
public ModelAndView makeAndSendInvoice(#PathVariable String email, ModelAndView mav) {
return mav; // <- Break point, debug !!
}
}
I am trying to submit a spring form via ajax but the values within the form are always coming across as null (The actual form is not null).
This is how I send the form from the JSP:
$('#fSystemSave').click(function() {
$.post("/live-application/systemSave", {systemForm: $("#systemForm").serialize()}, displayModifiedSystemResults, "html");
});
This is the form:
<form:form id="systemForm"
method="post" action="/live-application/systemSave"
commandName="systemForm">
<tr>
<td colspan="1" align="left">
<strong>SYSTEM SETTINGS</strong>
</td>
</tr>
<tr>
<td valign="top">Name: </td>
<td valign="top"><form:input path="fName" size="20" /> </td>
</tr>
<tr>
<td valign="top" align="left">
<button type="button" id="fSystemSave">Save</button>
</td>
</tr>
</form:form>
And this is the Java controller side:
#RequestMapping(value = "/systemSave", method = RequestMethod.POST)
public void saveSystem(#ModelAttribute("systemForm") SystemForm systemForm, OutputStream outputStream) throws IOException {
logger.info("Save System1: " + systemForm);
logger.info("Save System2: " + systemForm.getfName());
}
So 'Save System1' returns an Object tostring and 'Save System2' returns null. Can anyone spot what I am doing wrong?
Thanks,
I don't know Spring but I think {systemForm: $("#systemForm").serialize()} should just be $("#systemForm").serialize().