Spring mvc check if was BindingResult in javascript response - ajax

Is there a clear way to check if ajax success response controller returned view with validation errors?
controler:
if(result.hasErrors()) {
return "place/add";
}
javascript:
$.ajax({
url : "<spring:url value="/place/add"/>",
type : 'POST',
data : $("#newPlaceForm").serialize(),
success : function(response) {
How do I check if the response has no validation messages?

It's more clear to generate a HTTP response code to indicate the error.
For example: response.sendError(400, "Validation failed")
jQuery will execute the provided error handler based on the response code.
$.ajax( '/your/url').error(function (jqXHR) {
if (jqXHR.status == 400) {
console.log('Bad Request');
}
});
This is more clear since handling errors in a success handler doesn't make much sense. The failed request is also easier to debug with your browsers developer tools.

success : function(response){
if(response.status == "SUCCESS"){
// success code
}else{
// show validation errors
errorInfo = "";
for(var i =0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
}
$('#errorId').html("Please correct following errors: " + errorInfo);
}, error: function(e){
alert('Error: ' + e);
}

I ended up with:
success : function(response) {
try {
var status = $.parseJSON(response);
if (status.status = 'OK') {
alertify.success("Akcja wykonana pomyślnie");
$("#newPlaceForm").hide();
$("#spotPlaces").show();
}
} catch (e) {
$("#newLocationBox").html(response);
}
}
and it seems clear for me, I dont't have to search for errors in html code, if everything goes Ok I just return in controller view which only has ${status} field and I add attribute status as stringified Json model.addAttribute("status", "{\"status\": \"OK\"}");

Related

Async XMLHttpRequest not returning response when followed by code to redirect to another URL in Firefox and Safari

I am facing problem with my code in FireFox and Safari as below:
xhr = new window['XMLHttpRequest'];
xhr.onreadystatechange = function() {
if (done || xhr.readyState != 4) {
return;
}
done = true;
handleResponse(xhr.responseText, callback);
};
}
xhr.open('GET', uri+params, true);
xhr.withCredentials = true;
xhr.send(null);
function handleResponse(responseText, callback) {
var error;
var result;
try {
result = toucan.JSON.parse(responseText)['result']; //connectedAuth
logout result.
} catch (ex) {
result = undefined;
}
console.log("Result is" + result);
if (!result) {
var errorCode = 'UnknownError';
var errorMessage = 'An unknown error ocurred';
error = toucan.Base.format('%s: %s', errorCode, errorMessage);
}
invokeCallback(error, callback);
}
This is followed by redirection as :window.location.href = "index.php?module=login&method=logout";
However, I am not getting any response back from the request I made if it is followed by redirection in FireFox.
This works fine in Chrome but not in Firefox and is specific to the case when request is followed by redirection.
I do not have control on redirection code to be changed. Is there a way that the browser can be enforced to first complete the request and get the response before going for redirection while keeping the call asynchronous.
I would suggest you to use a promise, first create a function that run the ajax call that return the response from your server:
ajax_AuthUser(id,pass){
return $.ajax({
method: "POST",
url: "authUser.php",
data: { id: id, pass: pass}
})
}
Second use a done statement:
ajax_AuthUser(id,pass)
.done(function(response){
//check the response here !! maybe validate the json ?
var auth = JSON.parse(response)
if(auth.response == "approved"){
//do something here
}else{
//do other stuff here
}
}).fail(function(response){
//do something if fail
}).always(function(){
//do something after the call finished
})
If you want a live example here is a jsfiddle that show how promises work
Hope it helps

Retrieving of Restful web service values in android for Titanium

We are using the same restful web service code from serviceutility.js for both android and ios. But the service is getting hit and values are retrieved only in ios. The same code is not working in android and we are getting the following error:
[ERROR] : TiExceptionHandler: (main) [2,821093] - In alloy/controllers/home.js:25,32
[ERROR] : TiExceptionHandler: (main) [0,821093] - Message: Uncaught TypeError: Cannot read property 'status' of null
[ERROR] : TiExceptionHandler: (main) [0,821093] - Source: if ("1" == response.status) alert(response.message); else if ("0"
[ERROR] : V8Exception: Exception occurred at alloy/controllers/home.js:25: Uncaught TypeError: Cannot read property 'status' of null.
Titanium SDK is 5.1.2 GA
exports.login = function(user, cb) {
var response = null;
if (Ti.Network.online) {
var xhr = Ti.Network.createHTTPClient({
timeout : 10000,
validatesSecureCertificate : false
});
xhr.onload = function() {// Onload
var responseTxt = this.responseText == '' ? '{}' : this.responseText;
try {
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
} catch(e) {
cb(response, 'ERROR');
}
};
xhr.onerror = function(e) {
if (xhr.status === 0) {
cb(response, 'TIMEDOUT');
} else {
cb(response, 'ERROR');
}
};
url = "https://";
var postData = {
employeeId : user.employeeId,
password : user.password
};
xhr.open('POST', url);
xhr.setTimeout(10000);
xhr.setRequestHeader('employeeId', user.employeeId);
xhr.setRequestHeader('password', user.password);
xhr.send();} else {
cb(response, 'NO_NETWORK');
}};
The below code is for index.js file where the actual retrieval of values happen.
if (Ti.Network.online) {
loginUtil.login(user, function(response, status) {
Ti.API.info("status----" + status);
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
});
}
Please help us on this.
Looks like you are ONLY returning a string value instead of the entire response object. Then in your controller you attempt to access the .status property of the response object.
//this line returns the string responseTxt
response = JSON.parse(responseTxt);
Try returning the entire response object instead.
response = JSON.parse(this);
Then in your index.js controller use/ display the status property
alert(response.status);
Your index.js expected response to be an object, but that is only the case where you call callback like this:
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
All other places where you call callback the response variable is null, since that is what you initialise it with on the second line.
Your callback returns two parameters, response & status, the second param is never used.
From reading the login function code, you only get to access the response object if status == "SUCCESS"
if(status === "SUCCESS"){
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
}
else {
alert("whoops, please try again !"); // a more generic message.
}

Random HTTP error 405 while using ajax request

I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}

Unauthorized AJAX request succeeds

I have following controller method:
[HttpPost]
[Authorize(Roles="some_role_actual_user_is_NOT_in")
public ActionResult AJAXMethod()
{
return Json(new { message = "server message");
}
and page with script:
function sendReq()
{
$.ajax({
type: "POST",
data: { somedata: "somedata" },
url: "/Path/To/AJAXMethod",
success: onAJAXSuccess,
error: onAJAXError
});
}
function onAJAXSuccess(response, status, xhr)
{
alert("success: " + response.message);
alert(status);
}
function onAJAXError(xhr,status,error)
{
alert("error: " + status);
alert(error);
}
When I call sendReq with user not in the authorized role the AJAX call still suceed - callback onAJAXSuccess is called, but response.message is undefined.
This is correct behaviour. The success of an AJAX call is only determined by the fact the the server responded with a 200 OK. You will need to interrogate the returned response yourself to ensure it is in the format you expect.
For example:
if (typeof response.message != "undefined" && response.message != "") {
// it worked
}
else {
// didn't work || user did not have access.
}

optional $.ajax call

I have html.actionlink in my asp.net MVC 3view and jquery ajax call on link click. In my action method suppose I have this:
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Content("");
Ajax call is:
$(function () {
$('#checkExists').click(function () {
$.ajax({
url: $('#checkExists').attr('href'),
global: true,
type: 'GET',
timeout: 5000,
success: function (data) { //invoke when receive response from server
if (data != null && data.Error != '') //return failed
{
alert(data.Error);
}
// else {
// alert('error occurs 1');
// //action ok here
// }
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr + ajaxOptions + "Cannot connect to server to load data"); //sever is not available
},
complete: function () { //ajax done
//alert('complete');
}
});
return false;
});
In case of else , ajax i called, how can I stop $.ajax call ?
you have already made the ajax call there is no way you can undo it in your current scenario
what you can do is send a doNothing response
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Json(new { Message = "do nothing" }, JsonRequestBehavior.AllowGet);
and in the ajax success callback
success:function(data){
if(data.Message==='do nothing'){
// simply do nothing
}
}
jsut as a side note you can cancel the ajax call before you have instantiated it see this SO answer Abort Ajax requests using jQuery
update
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Content("");
and in the success callback
success:function(data){
if(!data.Message)
//alert(data); //content will be shown
}
What do you mean by stop the AJAX call? You already sent the AJAX call and it hit the controller action. It is this controller action that returned a JSON or a plain text. But at this stage it is too late to stop something that was already done. It's ike trying to bring someone back from death.

Resources