REST #FormParam values are null - java

I have the following in html
<form name="myform" method="POST">
<input type="text" id="products" name="products" />
</form>
function myForm() {
var url = 'rest/products/details/';
var formData = $("#myform").serializeArray();
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
In Java server side I have the following
#POST
#Path("/details")
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....
log.info("prod "+products); --> getting null
For some reason products is null even though I am passing correct values from html. What could be the reason for this?

function myForm() {
var url = 'rest/products/details/';
var formData = "products=asasa" ;
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
try this and remove #consumes annotation. the problem is in the $("#myform").serializeArray() function from jquery.

Try Consumes annotation
#POST
#Path("/details")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....

Issue is rather silly,I was using name instead of id and that resulted in getting null in server side for all form elements. I have changed to
<form id="myform" method="POST">
it works well
However
<form name="myform" method="POST"> doesn't work.

Related

Ajax request is not calling Spring boot controller

I'm trying to call my Spring controller using Ajax and submitting a form.
Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.
My main.js file and controller are placed in the following order:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
My controller is called PrivateAreaController
Ajax Code
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '#Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
Spring code
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML form
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
EDIT:
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?
In the HTML
<html>
<head>
<link id="contextPathHolder" th:data-contextPath="#{/}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
THEN IN JS
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + 'action_url', function() {});
What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..
Well. I never seen this part before.
#Url.Action("callingcontroller","PrivateAreaController")
I normally do like as below:
$.ajax({
type : "POST",
dataType: "json",
url : '/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
But it can have a problem with the contextPath.
So, What I do is adding 'request.getContextPath()/' as below:
$.ajax({
type : "POST",
dataType: "json",
url : '${request.getContextPath()}/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
The contextPath has the URL of your start page.
For instance, 'www.google.com' or 'www.naver.com'
But in general, Since I personally use the contextPath a lot, I make a value and keep it.
var context = ${request.getContextPath()};
Then, your code will look neat and easy to reuse.
And also you can figure it out with the error attribute.
error : function(err) {
console.log("not working. ERROR: "+JSON.stringify(err));
}
I hope this works out.

Spring MVC - Trouble with AJAX form posting

I'm having a trouble when posting a form with AJAX.
Here is my ajax call:
function submit() {
$.ajax({
type: "POST",
url: "http://localhost:8080/executeRetrieve",
data: $("#form").serialize(),
dataType: "json",
success: function(data) {
alert(data);
}
})
}
And here is my HTML form (They're in the same page):
<form id="form" method="post">
User <input type="text" name="user" id="user"/><br />
Password <input type="password" name="password" id="password"/><br />
<input type="submit" value="Submit" onclick="submit()"/>
And also, this is my action:
#RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public #ResponseBody String executeRetrieve(HttpServletRequest request) {
JSONObject json = new JSONObject();
json.put("message", "hello");
return json.toString();
}
I'm confused. Shouldn't that work? I've been searching for a solution for at least 3 days and I can't get to understand what's happening. The action method isn't even being reached. Would someone know where I am making a mistake?
Thanks in advance, pals.
I think there is issue in URI that you are trying to call from ajax http://localhost:8080/executeRetrieve. It should contains the application name deployed in server as well. e.g. http://localhost:8080/<app_name>/executeRetrieve

Can`t send information to server using ajax [400 (Bad Request)]

I can't send json object to Java server using ajax. Browser console throws error:
GET http: // localhost: 8080 / MySpring / change? {% 22name% 22:% 22d% 22} 400 (Bad Request).
I use SpringMVC
HTML file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#load").bind("click", function() {
var inputText = $("#mytext").val();
var task = {name : inputText};
$.ajax({
url : "change",
crossDomain: true,
type: 'GET',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify(task),
success: function (response) {
var result = response.name;
$("#result_text").text(result);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="mytext" id="mytext">
</br>
<input type="button" name="load" id="load" value="Load">
</br>
<p id="result_text"></p>
</body>
</html>
#Controller
public class MailController {
#RequestMapping(value = "/change", method = RequestMethod.GET)
public #ResponseBody
Task change(#RequestParam String name) {
Task result = new Task();
result.setName(name);
return result;
}
}
Try this. Also instead of dynamically adding json just hard code the it like {"name":"test"}
$.ajax({
type: "GET",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
It's the problem with the controller mapping.
Your controller is expecting:
http://localhost:8080/MySpring/change?name=yourData
but you are calling
http://localhost:8080/MySpring/change?yourData
Consider also changing method from GET to POST according to http get length limit.
<script>
$(document).ready(function() {
$("#load").bind("click", function() {
var inputText = $("#mytext").val();
var task = {name : inputText};
$.ajax({
url : "change",
crossDomain: true,
type: 'GET',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify(task),
traditional : true,
success: function (response) {
var result = response.name;
$("#result_text").text(result);
}
});
});
});
</script>
Added traditional : true, in Ajax call

REST #FormParam is null

I have the following being passed from browser to server
Status Code:204 No Content
Request Method:POST
Content-Type:application/x-www-form-urlencoded
Form Data
json:{"clientName":"PACK","status":"success","message":"successful!"}
and in jsp code
var loginData = {
clientName: cList,
status: "success",
message: "successful!"
};
$.ajax({
url: subUrl,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
data: {
json: JSON.stringify(loginData)
},
success: function (data) {
handleLoginResult(data);
}
});
And in Java code I have
#POST
public Object persistResetPasswordLogs(#FormParam("clientName")
String clientName) {
try {
log.info("in rest method ??? "+clientName);
.......
.......
In server I am getting clientName as null.
What could be the reason for this and how can I resolve this?
AFAIK, there is no Jersey (JAX-RS) mechanism to parse JSON into form data. Form data should be in the form of something like
firstName=Stack&lastName=Overflow (or in your case clientName=someName)
where firstName and lastName are generally then name attribute value in the form input elements. You can use jQuery to easily serialize the field values, with a single serialize() method.
So you might have something that looks more along the lines of something like
<form id="post-form" action="/path/to/resource">
Client Name: <input type="text" name="clientName"/>
</form>
<input id="submit" type="button" value="Submit"/>
<script>
$("#submit").click(function(e) {
$.ajax({
url: $("form").attr("action"),
data: $("form").serialize(),
type: "post",
success: processResponse,
contentType: "application/x-www-form-urlencoded"
});
});
function processResponse(data) {
alert(data);
}
</script>
Have you defined the Requestmapping like this:
#POST
#Path("/submitclient") // your request mapping for 'subUrl'
public Object persistResetPasswordLogs(#FormParam("clientName") String clientName)
and html:
<form action="submitclient" method="post">
...
</form>
Also look at your json object. I believe you should send something like this:
var loginData = {
clientName: "dit" // get it from input
};
?

the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false

I wanna send an image through ajax but I get the following exception:
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false
surprisingly when I send this form regularly(not through ajax) form works fine.I tried changing Content-Type to multipart/form-data but then I get this exception:
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
here is the jquery code:
$(document).ready(function() {
$("#myform").submit(function(e) {
e.preventDefault();
var data = new FormData();
data.append('file', document.formName.file.files[0]); // <-- possibly this line doesn't work
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});
and the form:
<form name="formName" enctype="multipart/form-data" id="myform" action="upload.do" method="POST">
<input type="file" name="file" id="input-file" />
<br>
<input type="submit" value="Upload images" class="upload" />
</form>
Try this:
$(document).ready(function() {
$('.upload').click(function() {
var input = document.getElementById('input-file');
file = input.files[0];
var data = new FormData();
data.append('file', file);
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});

Categories

Resources