I am working on a project adding some Ajax to a Spring-MVC project. I removed the tags
<form:errors path="fieldName"/>
That would insert the error the JSP, now I am trying to make some Ajax code to display the errors on the page. can anyone should me how to updated the following code to display the error messages and NOT the errors?
success: function(response)
{
// we have the response
$('#error').hide('fast');
if(response.status == "SUCCESS")
{
$('#error').hide('fast');
alert("Thanks for submitting. We will get back to you as soon as possible.\n\n" + response.result);
$('#error').hide('slow');
}else
{
errorInfo = "";
for( i = 0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
$('#input').show('slow');
}
},
error: function(e){
alert('Error: ' + e);
}
});
The above code works to display the errors but not the error messages
below is my java code:
#RequestMapping(value = "/ajax.html", method = RequestMethod.POST)
public #ResponseBody
JsonResponse addMessage(#Valid
#ModelAttribute(value = "memberrequest") MemberRequest memberrequest,
BindingResult result) {
JsonResponse res = new JsonResponse();
if (!result.hasErrors()) {
res.setStatus("SUCCESS");
// Setting data over to RT
String Ticket = zzz.sentWebRequest(memberrequest);
/*
* Setting out the ticket number to be displayed to user
*/
Map<String, Object> model = new HashMap<String, Object>();
Ticket t = new Ticket();
t.setTicketDetails(Ticket);
model.put("ticket", t);
res.setResult(Ticket);
} else {
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
}
JSON Class:
public class JsonResponse { private String status = null; private
Object result = null;
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Object getResult() { return result; }
public void setResult(Object result) { this.result = result; }
}
Try response.result[i].defaultMessage instead of response.result[i].code.
response.result
There is no result attribute in response object according to XMLHttpRequest 2 by W3C
If you pass some text value in response form server end. you can get it response.responseText as a whole text.
Related
I made a post request method with Retrofit2 but I encountered this problem on my response.
Expected a string but was BEGIN_OBJECT at line 3 column 4 path $.SUCCESS
The response should be
{
"SUCCESS" :
{
"200" : "access granted",
"ra" : "approved",
"la" : "approved",
"ch" : "approved"
}
}
I uses this code for the post request
#POST("login")
Call<Post> createPost(#Body Post post);
And for the POJO class
public class Post {
private String anthony;
private String SUCCESS;
public Post(String name) {
this.anthony = name;
}
public String getSUCCESS() {
return SUCCESS;
}
}
For the method I use the following code
private void createPost() {
Post post = new Post("mypassword");
Call<Post> call = jsonPlaceHolderApi.createPost(post);
call.enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
Post postResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "S" + postResponse.getSUCCESS();
textViewResult.setText(content);
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
Does anyone know what's wrong with my code? I expected to get the response inside the "SUCCESS" json object.
You expect SUCCESS to be an object in your wanted response but you have defined it as a String in your Post class. You should use an object for SUCCESS instead.
public class Post {
private String anthony;
private PostSuccess SUCCESS;
public Post(String name) {
this.anthony = name;
}
public PostSuccess getSUCCESS() {
return SUCCESS;
}
}
public class PostSuccess {
#JsonProperty("200")
private String _200;
private String ra;
private String la;
private String ch;
}
How to return String data from the json inside a json.
One is a check to see if there is data. a 201 response should then lead to the data being turned into a string.
I have tried to the following but it does not work. What have I got wrong. Can anyone explain to me so I can learn this?
//the method I call on button press.
PhpResponse and getCervicalROM are the Model classes listed below. I try to Toast to make sure I am getting the String variable data. But nothing comes up.
public void downloadromdata() {
Call <PhpResponse> call = RetrofitClient.getInstance().getAPIService().getCervicalROM(ID);
call.enqueue(new Callback<PhpResponse>() {
#Override
public void onResponse(Call<PhpResponse> call, Response<PhpResponse> response) {
if(response.code() == 201)
{
PhpResponse phpResponse = response.body();
RACERVICALROT = phpResponse.getUser().getRACERVICALROT();
LACERVICALROT = phpResponse.getUser().getLACERVICALROT();
Toast.makeText(cervicaltest.this, RACERVICALROT + "&" + LACERVICALROT, Toast.LENGTH_LONG).show();
}else if(response.code() == 422){
Toast.makeText(cervicaltest.this, "No data found", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<PhpResponse> call, Throwable t) {
}
});
}
getCervicalROM model
public class getCervicalROM {
private String RACERVICALROT, LACERVICALROT;
public getCervicalROM(String RACERVICALROT, String LACERVICALROT) {
this.RACERVICALROT = RACERVICALROT;
this.LACERVICALROT = LACERVICALROT;
}
public String getRACERVICALROT() {
return RACERVICALROT;
}
public String getLACERVICALROT() {
return LACERVICALROT;
}
}
Phpresponse Model
public class PhpResponse {
private boolean error;
private String message;
private getCervicalROM user;
public PhpResponse(boolean error, String message, getCervicalROM user) {
this.error = error;
this.message = message;
this.user = user;
}
public boolean isError() {
return error;
}
public String getMessage() {
return message;
}
public getCervicalROM getUser() {
return user;
}
}
APIService
#FormUrlEncoded
#POST("getCervicalROM")
Call<PhpResponse> getCervicalROM (#Field("ID") String ID);
getCervicalROM is also name of index call. The PHP Slim Returns data in postman so this last stuff is most likely fine.
$app->post('/getCervicalROM', function(Request $request, Response $response)
{
if(!haveEmptyParameters(array('ID'), $response)){
$request_data = $request->getParsedBody();
$ID = $request_data['ID'];
$db = new spinalromdbupload;
$result = $db->ptexists($ID);
if($result == DATA_FOUND){
$user = $db->getCervicalROM($ID);
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'Data Aquired';
$response_data['user'] = $user;
$response->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else if ($result == DATA_NOT_FOUND){
$response_data = array();
$response_data['error']=true;
$response_data['message'] = 'No ROM data entered for this pt';
$response->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
the php file
public function getCervicalROM($ID){
$stmt = $this->con->prepare("SELECT RACERVICALROT, LACERVICALROT FROM
spinalromdb WHERE ID = ?");
$stmt->bind_param("s", $ID);
$stmt->execute();
$stmt->bind_result($RACERVICALROT, $LACERVICALROT);
$stmt->fetch();
$user = array();
$user['RACERVICALROT'] = $RACERVICALROT;
$user['LACERVICALROT'] = $LACERVICALROT;
return $user;
}
private function isIDExist($ID){
$stmt = $this->con->prepare("SELECT ID FROM spinalromdb WHERE ID =
?");
$stmt->bind_param("s", $ID);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
You should provide default constructors for your model classes if you add constructurs with parameters.
In PhpResponse class, add:
public PhpResponse() {}
In getCervicalROM class, add:
public getCervicalROM() {}
changed code status and code above works fine. In the PHP index file it should be 201 not 200.
I am using the JSON array to get the values from Db in Servlet. I am suing following code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
List<ProjectDto> act=new ArrayList<ProjectDto>();
act=ActivitiesDao.getActivitiesDetails();
JSONArray jsonarray= new JSONArray();
for(int i=0;i<act.size();i++)
{
JSONObject obj = new JSONObject();
//obj.put("issueno", quiz.get(i).getIssueno());
obj.put("projectName",act.get(i).getProjectName());
obj.put("projectDescription",act.get(i).getProjectDescription());
obj.put("currentStatus", act.get(i).getCurrentStatus());
obj.put("area", act.get(i).getArea());
jsonarray.put(obj);
}
System.out.println("Json in Servelt"+ jsonarray.toString());
response.getWriter().print(jsonarray.toString());
}
}
I am able to get value from DB successfully. I have printed value in console.
Now, I have defined one method in some other java file to convert the data in paragraphs. Now, I am calling that method in Servlet in following way:
//method:
public static List<String> convertParagraphs(String text){
List <String> convertedList= new ArrayList<String>();
if(text==null|| text==""){
}
else{
String[] paragraphs= text.split("\\|");
convertedList= Arrays.asList(paragraphs);
}
return convertedList;
}
calling this method in Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
List<ProjectDto> act=new ArrayList<ProjectDto>();
act=ActivitiesDao.getActivitiesDetails();
JSONArray jsonarray= new JSONArray();
for(int i=0;i<act.size();i++)
{
JSONObject obj = new JSONObject();
obj.put("projectName",act.get(i).getProjectName());
String ttextt= act.get(i).getProjectDescription();
obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
obj.put("currentStatus", act.get(i).getCurrentStatus());
obj.put("area", act.get(i).getArea());
obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
jsonarray.put(obj);
}
System.out.println("Json in Servelt"+ jsonarray.toString());
response.getWriter().print(jsonarray.toString());
}
}
Getters and Setters method:
public class ProjectDto {
private String projectName;
private String projectDescription;
private String currentStatus;
private String area;
private List<String> projectDescriptionList= new ArrayList<String>();
private List<String> currentStatusList=new ArrayList<String>();
public List<String> getCurrentStatusList() {
return currentStatusList;
}
public void setCurrentStatusList(List<String> currentStatusList) {
this.currentStatusList = currentStatusList;
}
public List<String> getProjectDescriptionList() {
return projectDescriptionList;
}
public boolean setProjectDescriptionList(List<String> projectDescriptionList) {
this.projectDescriptionList = projectDescriptionList;
return false;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDescription() {
return projectDescription;
}
public void setProjectDescription(String projectDescription) {
this.projectDescription = projectDescription;
}
#Override
public String toString() {
return "ProjectDto [projectName=" + projectName
+ ", projectDescription=" + projectDescription
+ ", currentStatus=" + currentStatus + ", area=" + area
+ ", projectDescriptionList="
+ projectDescriptionList + "]";
}
}
Issue: Now, I am printing the value of ProjectDescription List, it is returning the false value. I am not sure where i am doing wrong. I tried to resolve the issues in many ways but not able to resolve the issue. could you please correct me and suggest me about my issue.
Please find my ajax code in jsp
<script>
$.ajax({
type: "POST",
url: "./ProjectServlet",
success: function (responseText) {
var jsonData = JSON.parse(responseText);
var uniueTabs = getUniqueLists(jsonData);
for (var i = 0; i < uniueTabs.length; i++) {
$('#tabs').append('<li >' + uniueTabs[i].area + '</li>');
var div = '<div id="tab-content-' + i + '" class="tab-pane fade">';
for (var j = 0; j < uniueTabs[i].tabContent.length; j++) {
var obj = uniueTabs[i].tabContent[j];
div += '<p>' + obj.projectName + '</p>'+ '<p>' + obj.projectDescription + '</p>' + obj.currentStatus ;
}
$('.tab-content').append(div);
$('#tab-content-0').addClass('in active');
}
$('#tabs li').eq(0).addClass('active');
setListner();
function getUniqueLists(responseText) {
var resArr = [];
responseText.filter(function (x, i) {
if (resArr.indexOf(x.area) === -1) {
resArr.push(x.area);
}
})
//console.log(resArr);
return mergeDataAreaWise(resArr, responseText);
}
function mergeDataAreaWise(area, responseText) {
var tabList = [];
for (var i = 0; i < area.length; i++) {
tabList.push({
area: area[i],
tabContent: []
});
}
var prjlist;
var output;
var proh;
var status;
for (var i = 0; i < tabList.length; i++) {
for (var j = 0; j < responseText.length; j++) {
statuss = '<li>' + responseText[j].currentStatus + '</li>';
prjlist= responseText[j].projectDescriptionList;
/* output= prjlist.split("&");
proh=output.join("/n");
*/
//proh=prjlist.replace(/&/g, '<br>');
status =statuss.replace(/&/g, '<br>');
var Obj = {
projectName: '<h3>'+ responseText[j].projectName +'</h3>',
projectDescription: '<p>'+ prjlist + '<p>',
currentStatus: '<b>'+ "Current Status:" +'</b>' + status
}
var currentArea = responseText[j].area;
if (tabList[i].area === currentArea) {
tabList[i].tabContent.push(Obj);
}
}
}
console.log(tabList);
return tabList;
}
}
});
function setListner () {
$("#tabs a").click(function () {
$(this).tab('show');
});
}
</script>
Of course you will get the value as false.
in your setter you are returning a boolean, which does set the value of projectDescriptionList but finally returns the hard code false every time.
Solution,
In your getter-setter;
// optional, just stick to setter rules, set the value and don't return anything.
public setProjectDescriptionList(List<String> projectDescriptionList) {
this.projectDescriptionList = projectDescriptionList;
}
In your doPost inside the for loop, third part of code in question
act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt));
obj.put("ProjectDescriptionList" ,act.get(i).getProjectDescriptionList() );
obj.put("currentStatus", act.get(i).getCurrentStatus());
obj.put("area", act.get(i).getArea());
// I don't know why you wrote it twice.. I'm commenting it.
// obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
jsonarray.put(obj);
How do I get a JSON response in jQuery Ajax in Spring Mvc?
This is my ajax code :
$.ajax({
type: 'POST',
url: "fetch",
dataType: 'json',
data: {clientidedit:clientidedit},
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
Here is my service. this will return a string.How can i get each data in ajax response?
public String getAllClientDetails(String strCode){
// org.json.JSONObject resObjForTable = new org.json.JSONObject();
JSONArray array = new JSONArray();
JSONObject resObj = new JSONObject();
JSONObject resObjPrd = new JSONObject();
SabbModelDet detData = sabbDao.getDataForUpdate(strCode);
List<SabbModelPrd> listPrd = sabbDao.getServicesUpdate(strCode);
//JSONObject resObj = new JSONObject();
String clientId = detData.getClientid();
String clientName = detData.getClientname();
String customerBaseno = detData.getCustomerbaseno();
String category = detData.getCategory_1();
String clientcpt = detData.getClientcpt();
// add PKB and PRK
int fileact = detData.getFileact();
int b2b = detData.getB2b1();
int collection = detData.getCollection1();
String primaccno = detData.getPrimaryaccno();
String accmfromacc = detData.getAccmfromacc();
String accmtoacc = detData.getAccmtoacc();
if (StringUtils.isEmpty(clientId)) {
resObj.put("clientId", org.json.JSONObject.NULL);
} else {
resObj.put("clientId", clientId);
}
if (StringUtils.isEmpty(clientName)) {
resObj.put("clientName", org.json.JSONObject.NULL);
} else {
resObj.put("clientName", clientName);
}
if (StringUtils.isEmpty(customerBaseno)) {
resObj.put("customerBaseno", org.json.JSONObject.NULL);
} else {
resObj.put("customerBaseno",customerBaseno);
}
if (StringUtils.isEmpty(category)) {
resObj.put("category", org.json.JSONObject.NULL);
} else {
resObj.put("category",category);
}
if (StringUtils.isEmpty(clientcpt)) {
resObj.put("clientcpt", org.json.JSONObject.NULL);
} else {
resObj.put("clientcpt",clientcpt);
}
if (fileact>0){
resObj.put("fileact", org.json.JSONObject.NULL);
} else {
resObj.put("fileact",fileact);
}
if (b2b>0){
resObj.put("b2b", org.json.JSONObject.NULL);
} else {
resObj.put("b2b",b2b);
}
if (collection>0){
resObj.put("collection", org.json.JSONObject.NULL);
} else {
resObj.put("collection",collection);
}
if (StringUtils.isEmpty(primaccno)) {
resObj.put("primaccno", org.json.JSONObject.NULL);
} else {
resObj.put("primaccno",primaccno);
}
if (StringUtils.isEmpty(primaccno)) {
resObj.put("accmfromacc", org.json.JSONObject.NULL);
} else {
resObj.put("accmfromacc",accmfromacc);
}
if (StringUtils.isEmpty(accmtoacc)) {
resObj.put(" accmtoacc", org.json.JSONObject.NULL);
} else {
resObj.put(" accmtoacc", accmtoacc);
}
array.put(resObj);
for(int i=1;i<=listPrd.size();i++){
for(SabbModelPrd list:listPrd){
resObjPrd.put("checkservice"+i, list.getServices1());
resObjPrd.put("accountno"+i, list.getAccountno());
resObjPrd.put("translimit"+i, list.getTranscationlimit());
resObjPrd.put("protocol"+i, list.getProtocol1());
resObjPrd.put("clientid"+i, clientId);
resObjPrd.put("productid"+i, list.getProductid());
}
}
array.put(resObjPrd);
// resObjForTable.put("aaData", array);
return array.toString();
Please just add the following in App_Start/WebApiConfig.cs class in my MVC Web API project
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
You have to have a spring contoller class to access the ajax request and return a model view as the response.
sample controller
#RequestMapping(value="/create", method=RequestMethod.GET)
public ModelAndView createSmartphonePage() {
ModelAndView mav = new ModelAndView("phones/new-phone");
mav.addObject("sPhone", new Smartphone());
return mav;
}
Do a google search on AJAX and Spring to get a lot more examples.
EDIT
A service is not exposed to the controller level so it would be a better option to introduce a controller level.
I have WebService which is checking whether the email is already present in the database.
#RequestMapping(value = "/checkPersonEmail/{jClientSessionId}/{jClientSessionId}/{email}", method = RequestMethod.GET)
public boolean checkName(#PathVariable String jUserSessionId,
#PathVariable String jClientSessionId, #PathVariable String email)
throws Exception {
String decryptedClientKey = EncryptContetns
.getDecryptedvalue(jClientSessionId);
List<String> emailIds = dimPersonManager
.getEmailIdsByClientKey(Long.valueOf(decryptedClientKey));
List<String> emailIdList = new ArrayList<String>();
for (String ids : emailIds) {
emailIdList.add(ids.toLowerCase());
}
if (emailIdList != null && !emailIdList.isEmpty()) {
if (emailIdList.contains(email.toLowerCase())) {
return false;
} else {
return true;
}
} else {
return true;
}
}
Then I'm calling this service using a http.get method as show below.
AngularJS call
$scope.checkEmail = function() {
if (!appClient.isUndefinedOrNull($scope.person.email)) {
alert( $scope.person.email);
$scope.spinnerClass = "icon-2x icon-spinner icon-spin";
var serverConnect = serverUrl + 'checkPersonEmail' + '/' + jUserSessionId + '/' + jClientSessionId + '/'+ $scope.person.email;
$http.get(serverConnect).success(function(data, status) {
// alert(JSON.stringify(data));
if (data == "true") {
$scope.spinnerClass = "icon-hide";
$scope.msgClass = "text-success icon-ok";
$scope.message = "Available";
} else {
$scope.spinnerClass = "icon-hide";
$scope.msgClass = "text-error icon-remove";
$scope.message = "Not Available";
}
}).error(function(data, status) {
alert("Failure");
});
}
}
Whenever this checkEmail is called it is a HTTP Bad request(400).
Could be because you have two jClientSessionId and no jUserSessionId in the #RequestMapping ({jClientSessionId}/{jClientSessionId})?
You need to put #ResponseBody annotation on your checkName method, if your controller is not annotated as #RestController.