Can not call Spring controller when use ajax - ajax

I have a problem when use ajax with Spring
I want filter list result when I select region from select box or enter store name on screen so my idea is use Ajax to resolve this. But Ajax can not call to specific controller what is in url attribute of $.ajax
Below is my files:
JSP :
CSS id for is appliedStoreSearch
<form:form modelAttribute="appliedStoreInput" id="appliedStoreSearch">
<form:select path="regionId" cssClass="form-control">
<form:option value="" label="Toàn quốc"></form:option>
<form:options items="${listRegions}" />
</form:select>
<input type="email" class="form-control"placeholder="Tìm kiếm cửa hàng" name="storeNameInp" />
<div class="input-icon">
<i class="fa fa-search"></i>
</div>
</form:form>
Ajax
$(document).on('change','#appliedStoreSearch',function(e){
var input = $("#appliedStoreSearch").serialize();
e.preventDefault();
$.ajax({
url:"/promotions_controller/search_applied_store_ajax",
method:"POST",
contentType : "application/json;",
dataType:"json",
data:input,
success: function(data){
}
});
e.preventDefault();
});
Controller :
#RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces="application/json" )
public #ResponseBody List<AppliedStoreDto> searchAppliedStoreAjax( #ModelAttribute("appliedStoreInput")AppliedStoreInputDto appliedStoreinput){
System.out.println("in ra 1 so thu gi go");
List<AppliedStoreDto> listAppliedStore = null;
appliedStoreinput.setCompanyId(7);
try {
// get list applied store
listAppliedStore = promotionLogic.findAllAppliedStore(appliedStoreinput);
} catch (Exception e) {
logger.error(e.getMessage());
}
return listAppliedStore;
}
I have debugged Javascript then I retrieved data from form but Spring controller (/promotions_controller/search_applied_store_ajax) still can not be called by Ajax. There is not any things what is showed in console
Please help me, tks all!!!!

Given your ajax call has contentType of "application/json;" I would look at adding consumes = "application/json" to your RequestMapping and swapping ModelAttribute for RequestBody

Sean's answer is basically correct. Just adding the exact details. Function declaration should look like something like following
#RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces = { MediaType.APPLICATION_JSON_VALUE}, consumes = {
MediaType.APPLICATION_JSON_VALUE} )
public #ResponseBody List searchAppliedStoreAjax( #RequestBody AppliedStoreInputDto appliedStoreinput){

Related

AJAX shows different behaviors in an if/elseif-statement which is inside the success function [duplicate]

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

Use Form to send Email in Spring Boot using Thymeleaf

I want to implement a send mail form using Thymeleaf.
I have a page called start_page.html that contains this form :
<div class="w3-container w3-padding-64" id="contact">
<h1>Contact</h1><br>
<p>We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste. Do not hesitate to contact us.</p>
<p class="w3-text-blue-grey w3-large"><b>Catering Service, 42nd Living St, 43043 New York, NY</b></p>
<p>You can also contact us by phone 00553123-2323 or email catering#catering.com, or you can send us a message here:</p>
<form th:action="#{~/homePage/contact}" th:object="${contactMail}" method="post" target="_blank">
<p><input class="w3-input w3-padding-16" type="text" th:field="*{nom}" th:placeholder="#{homePage.nom}" required name="nom"></p>
<p><input class="w3-input w3-padding-16" type="text" th:field="*{prenom}" th:placeholder="#{homePage.prenom}" required name="prenom"></p>
<p><textarea class="w3-input w3-padding-16" type="text" th:field="*{message}" style="height: 250px;" th:placeholder="#{homePage.message}" required name="message"></textarea>
<p><button class="w3-button w3-light-grey w3-section" type="submit">[[#{homePage.envoyer}]]</button></p>
</form>
</div>
I have already implemented a controller for this form action
#Controller
#PropertySource(ignoreResourceNotFound = true , value = "classpath:messages.properties")
public class HomePageController {
#Autowired
private MailContactService mailService;
#RequestMapping(value = "/homePage/contact", method = RequestMethod.POST)
public String sendMessage(ContactMail contactMail){
mailService.sendContactMail(contactMail);
System.out.println("done");
return "/home/start_page";
}
}
I'm not getting the desired behavior: I though that my page will stay the same but my page is reloading.
I want to order the controller to do something without getting out of my page.
I googled and I found that I can send a service object to my page but I want to avoid this option if there is other solutions .
Thank you.
You'll need to use an AJAX call if you don't want to refresh your page.
What this means is that you want to intercept the default HTTP form post behavior (that will do a full page refresh) using javascript.
For this you need to :
Remove the action tag on your form (let javascript handle it when clicking the button to submit the form)
Add this to your page (will be executed when the form is submitted :
$(document).ready(function () {
$("#contact-form").submit(function (event) {
// do not post the form and trigger full page refresh
event.preventDefault();
var formData = .. // construct some formData
$.ajax({
type: "POST",
contentType: "application/json",
url: "/homePage/contact",
data: JSON.stringify(formData),
dataType: "json",
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
For a full example, as always, mkyong.com has got you covered :)

Spring mvc Ajax search Form with Thymeleaf

I'm trying to add a search form in the navbar on every page in my spring mvc web app, just like the one here on stackoverflow, and I'm having issues. Right now I have a working search functions on a couple of my pages, using the typical mvc forms. I take the inputted string and store a variable called "searchString" in an object I created called "searchForm.java". Then I try to query that inputted string in the database using spring data's findbycontaing method, and then put that result on the model, and then represent that on the view, using thymeleaf. However I think that the navbar should be done using ajax, since it's on every page and pages with other forms.
So I think I'm sending the string that was submitted to the search form in the navbar to the controller where I queried it in the repository to bring back search results, then I tried to put the search results on the model, but I get nothing, all it does is redirect me to the search page. I may not be making very much sense, but I'll show my code, and if anyone could let me know if I'm going about my problem in the right way or not, and if you guys see any errors in my code. Thanks in advance.
So here's my ajax and jquery to submit the form.
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "navSearch",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
There may be an issue here, because in the console in the chrome developer tools, before it redirects, a message pops up very quickly that says uncaught TypeError: Cannot read property 'toLowerCase' of undefined, and it's coming from jquery.min.js:5 so that could be my issue, but I have no idea how to go about fixing this, and I've searched for answers so far with no luck.
Here's my html form, I think this shouldn't be a problem, but who knows, so I'll put it up anyways. And I'm using thymeleaf for this view.
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="submit" class="btn btn-default" id="searchButton">Search</button>
</form>
Here's my searchForm.java class, where I temporarily store the string to be queried in the database.
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
And Here's my controller, where I'm trying to handle the ajax submission and return it as search results on the setSearch.html page. What I'm thinking here is that the string "newSearch" from the form could be matched using the Spring Data query methods, and then be able to return it and add it to the model, but it's not working, it's just redirecting me to the /searchSet page with no data, because that's where the form action goes and that's what I tell it to return. So honestly I'm no sure if any data is even getting to this point.
#RequestMapping(value="setSearch/navSearch", method=RequestMethod.POST)
public #ResponseBody String navSearch (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
And here's an example of a working search method that I have in my controller that I use on a regular form, with no ajax, on the /searchSet page.
#RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
#RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(#ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
UPDATE
I've changed my code in the form from <button type="submit" class="btn btn-default" id="searchButton">Search</button> to <button type="button" class="btn btn-default" id="searchButton">Search</button> and now I get the Uncaught TypeError: Cannot read property 'toLowerCase' of undefined from earlier and nothing happens with the page.
UPDATE
I can now submit the ajax form without a problem, I was missing meta tags in the header, so the csrf wasn't submitting correctly, so now I get this error in the chrome developer tools console XHR Loaded (navSearch - 405 Method Not Allowed - 7.265999971423298ms - 634B)
UPDATE
Now everything works on the Ajax side, I needed to adjust my url to match the url I had in the request mapping on the controller and it runs through all the code fine. However the overall search function still doesn't work, here's my updated controller.
I know my issue here is that I'm returning a string and not an object, but I'm not sure how to return the object and then redirect the url to the /setSearch page. It's running through the code and returning a string "setSearch" in the console, because I told it to at the end of the controller.
#RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public #ResponseBody String search (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Here's my working ajax
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
but it's not working, it's just redirecting me to the /searchSet page
with no data, because that's where the form action goes and that's
what I tell it to return
You are right, it is because you are submitting the form and in the action you specify it to submit to setSearch, that is why the page is getting redirected to the same page. Just replace button type="submit" with button type="button" so that the form will not be submitted when searchButton is clicked.

Spring MVC Ajax Search Form Thymeleaf

So I'm trying to create a search form in the navbar of my site, and I'm using ajax to submit the form. I have other working search forms in my web app so I know how to do that. And I have the ajax submitting properly. I just don't know how to get the data from the form and use it in the controller to get the result that I want.
The way I'm doing the search function is by creating a searchForm.java object that has a string variable called searchString and I populate that and then query it against the database in the controller using spring data methods in my repository class.
So here's what my jquery ajax form looks like, and in the console on the chrome developer tools it returns "setSearch" like I tell it to in the controller, and I know that's an issue, I just don't really know how to fix it.
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
Here's my thymeleaf html page
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="button" class="btn btn-default" id="searchButton">Search</button>
</form>
This is my searchForm.java object
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
Here's my controller, and I know this won't work, because I'm returning a string and not a json object(I think that's right). But I tried to change it and I get a lot of errors, and I'm not sure how I should go about this.
#RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public #ResponseBody String search (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Here's a working example of a non ajax search function in my controller, so you guys can see what I'm trying to do.
#RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
#RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(#ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Let me know if I left anything out or if you would need to see any more code to see my issue. Thanks in advance.
If you are only submitting one parameter and it will be restfull there is no need for form or POST
Here is a simple example of how I would do a search that returns a array of objects from database. I hope you can use it to implement what you need.
HTML
<form>
<label for="search_input">Search:</label>
<input type="text" id="search_input">
</form>
Javascript
<script>
$.get("/search", {term: $('#search_input').val()}, function(data) {
// do your data manipulation and transformation here
});
</script>
Controller
RequestMapping("/search")
public #ResponseBody List searchPost(#RequestParameter("term") String query) {
List<Object> retVal = getListOfObjectFromDbBasedOnQuery(query);
return retVal;
}
Lot simpler (from a logical perspective), remember in RESTfull terms post is used to create objects. Retrieving data use GET only.

Spring and Ajax

Can I use spring form tag library in conjunction with Ajax?
I'm not able to retrieve the form input parameters inside the controller. They are always null.
Actually there is a logic that the form is never submitted. But then I can only send strings to my controller and not an object as happens with a form submit that gets mapped to a Spring commandBean.
Form accepting the commandBean
<form:form method="POST" commandName="clinicBean">
Clinic Name: <form:input path="name" type="text" /><br/>
Clinic Address: <form:input path="address" type="text"/><br/>
<input type="button" value="Create Clinic" onclick="clinicAjax()"/>
</form:form>
Ajax function calling the Spring controller
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
type: 'POST',
success: alert('Ajax Successful')
});
}
Spring Controller method:
#RequestMapping(value="clinicAjax",method=RequestMethod.POST)
public #ResponseBody String createClinic(#ModelAttribute("clinicBean") Clinic clinic){
System.out.println("Ajax call successful");
System.out.println(clinic);
System.out.println(clinic.getName());
System.out.println(clinic.getAddress());
return "SUCCESS";
}
It always gets null in the System.out.println() statements.
The problem is that you're not serializing your form anywhere so it's not being sent to the server.
Change your javascript code to:
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
data: yourFormElement.serialize(); /* i.e. $('#formId').serialize(); */
type: 'POST',
success: alert('Ajax Successful')
});
}
substitute yourFormElement with jQuery object representing your form and it should work.

Resources