Ajax request is not calling Spring boot controller - java

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.

Related

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 values are null

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.

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
};
?

jQuery setting input field value

I have a form to edit user and i would like to insert user data from database into forms' fields. What i do is
Link
Edit
Script
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
}
Form
<div id="edit-form" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<form:form>
<fieldset>
<label for="elogin">Login</label>
<input type="text" name="elogin" id="elogin" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form:form>
</div>
My Spring controller returns following(in wrapper i have field login)
#RequestMapping(value="/edit/{userLogin}", method=RequestMethod.POST)
#ResponseBody
public Wrapper edit(#PathVariable String userLogin) {
return wrapper.wrap(userService.findByLogin(userLogin));
}
But the form is empty. I also tried to set manual values but still no use. Please help me set input field value.
You should send your form data with your post request.
$.ajax({
url: url,
type: "POST",
data:$('form').serialize(),
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('#elogin').val(resp.login);
}
})
}
Should work just fine, as you've set an ID for the input.
Not quite sure you have the order right, surely you would make the ajax call first and then open up the jQuery dialog?
Either way, you could supply data into the dialog as follows;
//call ajax method to get value you want to show.
var somevariable = etc.....
var dto = {
loginName: somevariable
}
$( "#edit-form" ).data('params', dto).dialog( 'open' );
Then in your dialog use the open() method.
$("#edit-form").dialog({
bgiframe: true,
autoOpen: false,
height: 280,
width: 320,
draggable: false,
resizable: false,
modal: true,
open: function () {
//so values set in dialog remain available in postback form
$(this).parent().appendTo("form");
//get any data params that may have been supplied.
if ($(this).data('params') !== undefined) {
//stuff your data into the field
$("#elogin").val($(this).data('params').loginName);
}
}
});

java.io.EOFException Jackson Processor

I am using Spring MVC with the Jackson Processor. When a JSON request is sent to the server as a POST request, the #RequestBody is being deserialized into the object that I need. The problem comes when the GET request is sent, it actually displays Http 500 Internal Server error. The exception that is thrown is:
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal (MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments (HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
No emtpy strings are sent and the correct JSON is sent to the server. I am not sure why this is happening. Below is my code:
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
userId = form.find('input[name="userId"]').val(),
dat = JSON.stringify({ "userId" : userId });
$.ajax({
url : url,
type : "GET",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/user/find" method="GET">
<input type="text" name="userId" value="user1">
<input type="submit" value="Submit">
</form>
</body>
</html>
As soon as I change the request type to POST in the JSP and the controller method everything seems to work correctly.
package com.web;
#Controller
#RequestMapping("/user/*")
public class UserController {
#RequestMapping(value = "find", method = RequestMethod.GET, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
System.out.println("UserId :" + " " + user.getUserId());
return userResponse;
}
beans.xml
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
User.java
public class User implements Serializable {
private String userId;
public User() {
}
// Getters and setters
}
When a GET request is sent the broswer usually displays %%user%%. This is only an example. Does the Jackson processor will still read GET requests?
I don't know where the problem is. I hope you can help.
I read the following description on what the data parameter does in jQuey.ajax() does at http://api.jquery.com/jQuery.ajax/:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. ....
So it is appended to the URL and there is no request body. That is a behaviour consistent with the GET semantics, if you want to post data use POST.

Categories

Resources