how to call spring controller in jquery ajax success method - java

I have created a spring controller and a jsp page. In jsp page I am using jquery ajax call to hit the controller. Now, this controller returns a json response as string. Now on based of json response in success method, I want to call a next controller call which will return a ModelAndView jsp page. How can I do this. Below is my code:
JSP Jquery ajax call:
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
try{
var strResponse=jQuery.parseJSON(response);
}catch(err){}
if(response.status=='ok')
{
alert ("okokokokokokokokok");
//I am successfully reaching till here.
//But in case of this alert box I want to call a
//controller which will return ModelAndView and
//should open a corresponding ModelAndView jsp page.
//something like:
/*
$.ajax({
type: 'GET',
'url': 'http://localhost:8080/Test_ReportingUI/abcxyz.htm',
)};
*/
}
else
{
alert("ERROR!!");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
Controller class methods:
#RequestMapping (value="fieldMappingNext.htm", method=RequestMethod.POST)
#ResponseBody String addFieldMappingNext(#RequestParam String jsonData)
{
String customerID =null;
String objectID = null;
String syncFieldName = null;
String optMapping = null;
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(jsonData);
customerID = requestedJSONObject.getString("customerID");
objectID = requestedJSONObject.getString("objectID");
syncFieldName = requestedJSONObject.getString("syncFieldName");
optMapping = requestedJSONObject.getString("optMapping");
}catch(Exception exex){
exex.printStackTrace();
}
if(optMapping.equalsIgnoreCase("direct")){
long metadataID=rwCustomerService.getMetaDataID(customerID,objectID);
List<RWFieldDetail> list=rwCustomerService.getFieldDetailNames(metadataID);
request.setAttribute("customerID", customerID);
request.setAttribute("objectID", objectID);
request.setAttribute("optMapping", optMapping);
request.setAttribute("syncFieldName", syncFieldName);
request.setAttribute("fieldNames", list);
try {
jsonResponse.put("status", "ok");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonResponse.toString();
}
Second Controller method that I want to call from jquery success method:
#RequestMapping (value="abcxyz.htm", method=RequestMethod.GET)
ModelAndView fieldMapping(){
ModelAndView modelAndView=new ModelAndView("FieldMappingMainScreenNext");
return modelAndView;
}
How do I do this.

Since the second handler method returns ModelAndView, you should redirect from the success callback:
...
success: function(response) {
window.location.replace(response.url);
}
...

In your Java code you can use something like:
Map<String, String> map = new HashMap<String, String>();
if(condition1){
map.put("url","url1.html");
}
if(condition2){
map.put("url","url2.html");
}
Convert it to a JSON string and revert it back. Afterwards, in the jquery portion you'll get the response:
success:function(jsonStr){
var obj = JSON.parse(jsonStr);
var url = obj.url;
}
That is how you can get the url. If you want to load an other page or create an ajax call then you can do it.

Related

Ajax call Data not Binding

I am trying to bind my form with modelattribute in controller throught ajax call but i didnt get the values in bean e.g all values of bean are null
I printed the form data in alert() its showing me correct data but in controller its showing me null
This is my ajax call and console.log() print whatever i want but in controller i am not getting my data.
Ajax call ::
function viewBugReport(data) {
var formdata=$("#getAppForm_"+data).serialize();
console.log(formdata);
$.ajax({
url : 'displaybugreport.html',
data :formdata,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
alert(data);
}
});
}
Controller code ::
#ResponseBody
#RequestMapping(value = "/displaybugreport.html")
public String viewBugReport(#ModelAttribute BugReportBean1 bugreportbean,
HttpSession session) {
String ResultMessage = "something went wrong!!";
String adminId = "X";
System.out.println(bugreportbean);
try {
AdminBean adminBean = (AdminBean) httpSession.getAttribute(SESSION_KEY_ADMIN);
adminId = adminBean.getUserId().trim();
ResultMessage = bugReportService.submitBugReport(bugreportbean);
} catch (Exception e) {
logger.debug("GADG:" + adminId
+ " :: Exception occured :: viewBugReort POST method :: BugReportController class");
e.printStackTrace();
}
return ResultMessage;
}
As I can't see the full controller and you haven't mentioned any HTTP method in your desired endpoint, you can try like this:
#RequestMapping(value = "/displaybugreport.html", method = RequestMethod.POST)

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

How To Call Spring MVC Controller From JQuery Ajax Call

i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.
First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.
Javascript function:
function authenticatePricingCalcLogin() {
var login = {
userName : $("#username").val(),
password : $("#password").val()
};
$.ajax({type: "POST",
url: CONTEXT_PATH+"authenticateLogin",
data:JSON.stringify(login),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success: function (response) {
if (response != null) {
if (response.errorMsg != null && response.errorMsg != "") { // Login Error
alert(response.errorMsg);
} else {
// Here i need to call spring controller method and to redirect to another page
// I have tried
$.ajax({type: "GET",
url: CONTEXT_PATH+"navigateMainPage",
data:JSON.stringify(loginDO),
contentType : 'application/json; charset=utf-8',
dataType : 'json'
});
}
}
}
});
}
AuthController.java
#RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public #ResponseBody LoginDO authenticateLogin(#RequestBody Login login){
return authService.authenticateLogin(loginDO);
}
#RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(#ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
try {
// Need to set User Name in session variable
} catch (Exception e) {
}
return "auth/mainPage";
}
Please add / in your path
url: CONTEXT_PATH+"/authenticateLogin",
Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side #ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.

Angularjs http no response from Spring Boot

I'm trying to develop a small application to create index on local elasticsearch engine. I use angularjs on the front-end, and spring-boot on the back-end. It can create index successfully, however, when I want to retrive the response in the front-end, it keeps throwing me errors.
Below is my AngularJS api call:
app.service('ESIndexService', function($http) {
this.createESIndex = function(esindexObj) {
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj
};
return $http(settings).then(function(response) {
console.log("response:"+response);
return response;
}, function(error) {
console.log("error:"+error);
return error;
});
};
});
Then this is my controller:
#CrossOrigin
#RestController
#RequestMapping(value = "ESIndex")
public class ESIndexController {
#RequestMapping(value = "createESIndex", method = RequestMethod.POST)
public #ResponseBody String createIndex(#RequestBody ESIndex esIndex) {
try {
Settings settings = Settings.builder()
.put("xpack.security.user", String.format("%s:%s", Constants.ES_UNAME, Constants.ES_PWD)).build();
TransportClient client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constants.ES_HOST), Constants.ES_PORT));
CreateIndexResponse response = client.admin().indices().prepareCreate(esIndex.getName()).setSettings(Settings.builder()
.put("index.number_of_shards", esIndex.getNumberOfShards())
.put("index.number_of_replicas", esIndex.getNumberOfReplicas())).get();
client.close();
if(response.isAcknowledged() && response.isShardsAcked())
return Constants.SUCCESS;
else
return "Fail to create index!";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
I want to get the response status and data in AngularJS response. However, it keeps throwing me errors:
error:SyntaxError: Unexpected token i in JSON at position 0
I'm not using JSON.parse function, why it gives me error like this?
After adding responseType: 'text', still throwing same error, the chrome nextwork
It turns out I need to add "transformResponse: undefined", however, in another of my project, I never did this. What's the difference?
AngularJS:
this.newBlog = function(blogObj) {
var settings = {
method: 'POST',
url: baseUrl + "/blog/newBlog.do",
data: blogObj
}
return $http(settings).then(function(response) {
return response;
}, function(error) {
return error;
});
};
Java Controller:
#RequestMapping(value="newBlog.do", method=RequestMethod.POST)
public #ResponseBody String newBlog(#RequestBody Blog blog, HttpServletRequest request) {
User createdBy = (User) request.getSession().getAttribute("user");
if(createdBy == null)
return NO_SESSION_MSG;
else {
createdBy.setPwd(null);
blog.setCreatedAt(TQBUtilities.getCurrentTime());
blog.setLastUpdatedAt(TQBUtilities.getCurrentTime());
blog.setCreatedBy(createdBy);
return blogService.newBlog(blog);
}
}
Angular is automatically trying to parse the server response as JSON. Try adding this to your settings object
responseType: 'text'
So
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
responseType: 'text'
};
#jheimbouch add "transformResponse: undefined" to http call, like below, works fine:
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
transformResponse: undefined
};
However, why it is required in angularjs 1.6.2? When I was using AngularJS 1.4.8, I don't need to add transformResponse attributes.

Using ajax with Spring MVC

I am currently using the Spring MVC, and I am trying to do some stuff with ajax. Basically what I want to do now is display the result from a controller dynamically on a webpage.
I.E. A user pushes a button it goes to the "whatever.do" controller and gets a list and displays that list without having to reload that page.
Anyway does anyone know any good tutorials or example projects?
It is very simple, I don't even think a special tutorial is needed (apart from a generic spring-mvc one).
Make a #RequestMapping("/foo") method that returns a List<Foo>
Have <mvc:annotation-driven /> in your dispatcher-servlet.xml to activate handler mappings and convertors
Put Jackson (json serializer) on your classpath
Use $.getJSON("/foo", function(data) {..}); (jquery) - you will get a JSON-encoded list of your Foo objects
Spring will detect that the browser requests a json response, and converts your objects using Jackson.
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html
your controller must have in following format when you are using with spring along with ajax:
#RequestMapping(value = "/show.ajax", method = RequestMethod.POST)
public #ResponseBody List<your object type> your_method_name() {
//code logic
return list_of_your_object;
}
also your java script code on jsp page in following format:
<script>
function your_javascript_fun_name() {
$.ajax({
type : 'POST',
url : 'show.ajax',//this is url mapping for controller
success : function(response) {
alert(response);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
</script>
import jquery library in jsp page
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
var id = $("#id").val();
var resourceURL = $("#contextpath").val()+"/customer/retrivebyid/"+id;
$.ajax({
url : resourceURL,
type : 'GET',
dataType : 'json',
async : false,
success: function(data) {
var successflag = data.response.successflag;
var errors = data.response.errors;
var results = data.response.result;
if(successflag == "true"){
$.each(results, function (i, result) {
$("#id").val((result.id == undefined || result.id == null || result.id.length <= 0) ? "-" : result.id);
$("#name").val((result.customername == undefined || result.customername == null || result.customername.length <= 0) ? "-" : result.customername);
});
}else{
$("#errorMsgContent").html(errors);
$.fancybox.open('#errorMsg');
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#errorMsgContent").html(thrownError);
$.fancybox.open('#errorMsg');
}
});
#RequestMapping(value = "/retrivebyid/{id}", method = RequestMethod.GET)
public #ResponseBody String retriveUser(#PathVariable long id, Model model,HttpServletRequest request) {
String jsonresp = null;
try {
List<CustomerDO> customerList = new CustomerService().retriveById(id);
jsonresp = CustomerUtil.getCustomerList(customerList).toString();
} catch (Exception e) {}
if (jsonresp != null) {
return jsonresp.toString();
} else {
return null;
}
}
public static JSONObject getCustomerList(List<CustomerDO> empList)throws AppException {
JSONObject responseJSON = new JSONObject();
JSONObject resultJSON = new JSONObject();
try {
resultJSON.put(CommonConstants.SUCCESS_FLAG, CommonConstants.TRUE);
resultJSON.put(CommonConstants.ERRORS, "");
JSONArray resultJSONArray = new JSONArray();
for (CustomerDO customer : empList) {
resultJSONArray.put(getCustomerDetailObject(customer));
}
resultJSON.put(CommonConstants.RESULTS, resultJSONArray);
responseJSON.put(CommonConstants.RESPONSE, resultJSON);
} catch (JSONException e) {
e.printStackTrace();
}
return responseJSON;
}
private static JSONObject getCustomerDetailObject(CustomerDO customer)throws JSONException, AppException {
JSONObject result = new JSONObject();
result.put(CommonConstants.ID, String.valueOf(customer.getId()));
result.put(CommonConstants.CUSTOMER_NAME, String.valueOf(customer.getName()));
return result;
}

Categories

Resources