When cache false in set in ajax,it add some value in request what it is - ajax

I using a small code of Ajax and my code is working.There is no error in my code but when i set cache false in my ajax it add some value in request.I want to know What is the value and its purpose.
My code is
function validate() {
var user = $('#user').val();
var num = $('#num').val();
var mobile= $('#otp').val();
$.ajax({
type: "GET",
url: "/validateOtp",
data: {user: user , num: num , mobile: mobile},
dataType: 'text',
cache: false,
timeout: 600000,
success : function(response) {
alert( response );
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
it generate request like this in browser
http://localhost:8080/validateOtp?user=1234&num=12345&otp=1234&_=1528862398631
you can see the value added by ajax &_=1528862398631
and My backend code is in Spring MVC
#Controller
#RequestMapping("/validateOtp")
public class ValidateOTPAjaxController {
private final Logger logger =
LogManager.getLogger(this.getClass().getSimpleName());
#Autowired
private OTPService otpService;
#RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getAllDistrict(#RequestParam(value = "user") String user,
#RequestParam(value = "num") String num, #RequestParam(value = "mobile") String mobile) {
logger.debug(user);
logger.debug(num);
logger.debug(mobile);
return "OK";
}

By setting the cache property to false jQuery will append a timestamp to the URL, so the browser won't cache it (as the URL is unique for every request. See the documentation for details: http://api.jquery.com/jQuery.ajax/
And your controller should be like following:
#Controller
public class ValidateOTPAjaxController {
private final Logger logger =
LogManager.getLogger(this.getClass().getSimpleName());
#Autowired
private OTPService otpService;
#RequestMapping(value = "/validateOtp", method = RequestMethod.GET)
public String getAllDistrict(#RequestParam("user") String user,
#RequestParam("num") String num, #RequestParam("mobile") String mobile) {
logger.debug(user);
logger.debug(num);
logger.debug(mobile);
return "OK";
}
}

Related

Content type 'multipart/form-data;boundary=----WebKitFormBoundary...' not supported Spring

Spring 5.0.7: MVC, Data, Security.
I configure multipartResolver.
I send next Ajax request:
$.ajax({
type: 'POST',
cache: false,
processData: false,
contentType: false,
url: '/api/v1/category/add',
data: new FormData(form)
}).done(result=>{console.log(result);}).fail(result=>{
console.error('ERROR:', result.responseJSON.httpStatus, result.responseJSON.message, result);
self.toast.error('API Error.');
});
But there is an error: Content type 'multipart/form-data;boundary=----WebKitFormBoundary6xBCDjCtYYuUVR5c' not supported
why? i don't understand why error happen.
Controller:
#RestController
#Secured("hasRole('ADMIN')")
#RequestMapping(value = "/api/v1")
public class ApiController {
private static final Logger LOGGER = LogManager.getLogger(ApiController.class);
#PostMapping(value = "/category/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
private Response categoryAdd(Response response, #RequestBody CategoryAddForm categoryAddForm) {
LOGGER.info(categoryAddForm.toString());
return response;
}
}
CategoryAddForm:
public class CategoryAddForm {
private String name;
private String description;
private MultipartFile preview;
public CategoryAddForm() { }
public CategoryAddForm(String name, String description, MultipartFile preview) {
this.name = name;
this.description = description;
this.preview = preview;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public MultipartFile getPreview() {
return preview;
}
}
I do not know what else to write, but SO requires more text. (
In your controller, use #RequestParam instead of #RequestBody.
Was having the same issue and it worked for me.
See this SO answer for more info
You need to add this maven dependency commons-fileupload:commons-fileupload:1.3.x
and declare MultipartResolver bean
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
Above method is for Spring controllers. If you want to do for Async Spring controllers refer this article.
http://www.baeldung.com/spring-file-upload
Hope it helps!

Throw custom exception from Spring controller and receive it in ajax-post error function

So, i need to add custom validation to my page, the problem is, i don't have any form, i collect and send data almost manually, here is my ajax post:
$.ajax({
type: "POST",
url: "/settings/propertyedit",
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: {
propertyName : propName,
propertyValue : propVal,
Id : Id,
SettingId : SettingId,
},
beforeSend: function (xhr) {
xhr.setRequestHeader($.metaCsrfHeader, $.metaCsrfToken);
},
success: function (response) {
//Do some something good
},
error: function(response){
//do some something worning
}
});
And controller:
#Link(label = "property edit", family = "SettingsController", parent = "Settings")
#RequestMapping(value = "/settings/propertyedit", method = RequestMethod.POST)
#ResponseBody
public String atmpropertyedit(#RequestParam String propertyName,
#RequestParam String propertyValue,
#RequestParam Long Id,
#RequestParam Long SettingId) {
//Check if it is an error
//If correct i want to return some text in success function
//If error happens want to return some relevant text to error function
}
So, the point is, that validation is also custom, so i cant throw exception simply with try catch and if i am trying to do something like:
return new ResponseEntity<>(HttpStatus.NOT_EXTENDED);//Error type is for testing purposes
I will get 400 error even without triggering into my controller. At this point i just want some simple method to let know my ajax what has happened in my controller.
The controller can be as simple as this one, you can make it happen with custom response class which I named CommonResp and an Enum VALIDATION.
Controller - returns Response class.
#ResponseBody
public CommonResp atmpropertyedit(#RequestParam String propertyName,
#RequestParam String propertyValue,
#RequestParam Long Id,
#RequestParam Long SettingId) {
// error
if (!isValidPropertyName(propertyName)) return new CommonResp(VALIDATION.INVALID_PROPERTY_NAME);
// success
return new CommonResp(VALIDATION.OK);
}
}
CommonResp.java - will be the json response.
public class CommonResp implements Serializable {
private int code;
private String message;
public CommonResp() {
this(VALIDATION.OK);
}
private CommonResp(final int code, final String message){
this.code = code;
this.message = message;
}
public CommonResp(VALIDATION validation) {
this(validation.getCode(), validation.getMessage());
}
/* Getters and Setters */
}
VALIDATION.java
public enum VALIDATION {
OK(200, "OK"),
INVALID_PROPERTY_NAME(401, "PropertyName is not valid");
private int code;
private String message;
private VALIDATION(int code, String message) {
this.setCode(code);
this.message = message;
}
/* Getters and Setters */
}
Please let me know if there are any better implementations. (propably tons of, It's just that i don't know :P)

Spring - Stop redirection on error

I have a page to manage users and I would like to stay on the page if any error occurs when clicking save.
The only cases I found online where to do with validation.
Also my page requires the userId to be posted so I don't think returning the name of the original page in the controller would work. Also I would loose the changes made in the page.
What I am trying to achieve is stay in the same page, showing a message to the user.
Here is my controller:
#RequestMapping(method = RequestMethod.POST)
public String editUser(#RequestParam("userId") String userId, final Map<String, Object> model) {
User user = spiService.getUser(userId);
model.put("user", user);
configureRoles(model, user);
return "edituser";
}
#RequestMapping(path = "/updateUser", method = RequestMethod.POST)
public String updateUser(#RequestParam("userJson") String userRoles, #RequestParam("userId") String userId, final Map<String, Object> model) throws IOException {
User user = spiService.getUser(userId);
try {
addRoles(JsonUtil.getField(userRoles, "addedRoles"), user.getRoles(), userId);
removeRoles(JsonUtil.getField(userRoles, "removedRoles"), user.getRoles(), userId);
} catch (Exception ex) {
// What now?
}
return "users";
}
Instead of redirecting you can use Ajax calls in your controller. For that you have to create one AjaxPojoClass for exampleAjaxResponseBody as your convenience.
For example
$.ajax({
type : "POST",
contentType : "application/json",
url : "/yourUrl",
data : JSON.stringify(data),
dataType : 'json',
success : function(data) {
window.location.replace("/successUrl")
},
error : function(e) {
display(e);
},
});
AjaxController
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/yourUrl")
public AjaxResponseBody getSearchResultViaAjax(#RequestBody SearchCriteria search) {
AjaxResponseBody result = new AjaxResponseBody();
//logic
return result;
}
}
you can use ajax to submit your request.

Spring MV ajax form with serialize

I am trying call a spring mvc controller from a form in my page, this my controller.
#RequestMapping(value = "/editor/create", method = RequestMethod.POST)
public ResourceDTO create(#RequestBody ResourceCreateDTO dto)
throws Exception {
ResourceDTO responseDTO = null;
//Add the resourceCreate and gets the responseDTO.
return responseDTO;
}
This my ajax call:
$.ajax({
type: "POST",
url: context + "/editor/create",
data: $("#createForm").serialize(),
cache: false,
success:function(result){
},
error:function(){
}
});
I'm getting this response: HTTP 415
This mi form call data (From developer view on Chrome):
resource-id:1006
resource-name:asdf
resource-description:asdfasdf
resource-folder:0
resource-folder-type:1000
resource-scene-width:
resource-scene-height:
I only have to use filled fields in this option. Not problem for empty fields.
Mi ResourceCreateDTO (serializable) have this fields:
private Integer resourceTypeId;
private Integer resourceId;
private String resourceName;
private String resourceDescription;
private Integer folderId;
private Integer resourceType;
private Integer sceneWidth;
private Integer sceneHeight;
/**GETTERS AND SETTERS**/

JSON Posting to Spring-MVC, Spring is not seeing the data

I am working on a project that the project is going to use Ajax to post JSON object to Springs-MVC. I been making a number of changes and I got it to the point where I dont get any more errors BUT I dont see the data that is getting POSTed to Spring in the object I need it in.
Here is my Spring Controller.
#RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
public #ResponseBody JsonResponse addUser(#ModelAttribute(value="user") User user, BindingResult result ){
JsonResponse res = new JsonResponse();
if(!result.hasErrors()){
res.setStatus("SUCCESS");
res.setResult(userList);
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
I put a breakpoint in and my USER object never gets the data. next is a copy of my USER object:
public class User {
private String name = null;
private String education = null;
private List<String> nameList = null;
private List<String> educationList = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
public List<String> getEducationList() {
return educationList;
}
public void setEducationList(List<String> educationList) {
this.educationList = educationList;
}
and now for the javascript code that does the Ajax, JSON post:
function doAjaxPost() {
var inData = {};
inData.nameList = ['kurt','johnathan'];
inData.educationList = ['GSM','HardKnocks'];
htmlStr = JSON.stringify(inData);
alert(".ajax:" + htmlStr);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: contexPath + "/AddUser.htm",
data: inData,
dataType: "json",
error: function(data){
alert("fail");
},
success: function(data){
alert("success");
}
});
};
Please let me now if you can help?? I have to get this working ASAP... thanks
You also need to specify the header in your RequestMapping annotion found in your controller.
#RequestMapping(headers ={"Accept=application/json"}, value="/AddUser.htm", method=RequestMethod.POST)
Also, remove .htm in your URL path. htm is some kind of request type overide. Using .htm specifies the web server to handle the request as a classic html request. Using .json would specify to the webserver that the request expects to be handled as a json request.

Resources