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