optional $.ajax call - ajax

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.

Related

Routing through AJAX

I have an ajax request handling validation of form fields (login+signup+forget password). In its success scenario, I want it to route to another page, but when I use Redirect::route('name'); as return from controller, it completes the request with 200 and generates another GET request which just returns the html as response and does not route to other page.
AJAX
$('form[data-remote]').on('submit', function (e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
beforeSend: function () {
$('#ajax-loading').show();
$(".has-error").text("");
$('#login-error').addClass('display-hide');
$('#forget-user-error').addClass('display-hide');
}
})
.done(function (data) {
if (data.signup_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.email_fail) {
$('#email_error').text('This Email already in use against an account.');
}
else if (data.company_fail) {
$('#email-error-popup').trigger('click');
}
else if (data.login_fail) {
$('#login-error').removeClass('display-hide');
}
else if (data.forget_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});
How can I route to the other page on success condition? The ajax is triggered on a form submit button.
As you are doing an ajax request you can't just redirect from the controller on successful validation. Instead, just return the url you want to redirect to, as response to the ajax request similar to the way you are returning the validation errors. And in your js file use that url to redirect to new page.
#your above code
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else{
window.location.replace(data.redirect_url); //this will redirect to new page
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});

Spring mvc check if was BindingResult in javascript response

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\"}");

HTML.ActionLink redirect not stopping with return false in $.ajax()

i've a HTML.ActionLink on view. what i'm doing is i'm making call to $.ajax() function which checks for return true or false from an anction. it hitting the action, returning the desired result true/false. but the problem is when it returns false. i need to show an alert and redirect should be only in case if its return true..
ActionLink:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick="return checkFleetAddedandScroing()"}) %>
Function:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
alert('Ok button clicked');
return true;
}
else {
alert("Cannot delete this fleet becasue either you have already added races to this event or the fleet has used for boat registration.");
return false;
}
}, //success
error: function (req) {
}
});
}
it redirects always..whether it returns true/false..it should redirect only if it returns true....
Please correct me where i'm doing wrong..
You're returning false from the AJAX callback.
That has nothing to do with the return value from the outer function; the AJAX callback won't even start running until later.
you must wait for your request to receive the result, and for doing this set async parameter of ajax function to false.
EDIT: you are lucky with your scenario. you can always return false and in case of successful delete call a function named DoRedirect.
this is the way to go :
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
timeout: 30000,
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
alert('Ok button clicked');
DoRedirect();
}
else {
alert("Cannot delete this fleet becasue either you have already added races to this event or the fleet has used for boat registration.");
}
}, //success
error: function (req) {
}
});
return false;
}
function DoRedirect(){
//code for do redirect
}
cheers!

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

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.
}

Resources