How to get(handle) Error (Not Acceptable & Internal Server Error) Exception content in Ajax - ajax

I added internal Error (throw exception) in server side. Now I want to handle this error in client side. However , I get error content undefined.
I am using Postman , and see my response is JSON format, it has response parameter like "Message". I tried to parse JSON , and again I got Cannot read property 'Message' of undefined
Ajax function defined like this:
function Ajax(url, method, json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
url: url,
data: json,
type: method,
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GlobalAuthToken);
},
processData: false,
dataType: 'json',
success: function (data) {
successFunction(data);
},
error: function(event, jqxhr, settings, thrownError) {
if (errorFunction != null) {
errorFunction();
}
}
});
}
I used this function in my code , error part like this, In this function how can I get exception content?
function(event, jqxhr, settings, thrownError)
{
alert("ERROR HAPPENED");
var responseString = JSON.stringify(event);
alert(responseString.Message);
alert("event" + event.Message);
},
Postman Result:
{
"Message": "Please select corresponding template."}
Expected Result should be : Please select corresponding template.

I solved the problem, if you face this kind problem , trying like this:
function showAjaxError(event, jqxhr, settings, thrownError) {
var msg = "";
if (event.hasOwnProperty('responseJSON')) {
var resp = event['responseJSON'];
msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.ExceptionMessage : "");
if (resp && resp.hasOwnProperty('InnerException')) {
msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.InnerException.ExceptionMessage : "");
}
} else {
msg = event.responseText;
}
}

Related

Combine AJAX and API calls

I am working with APIs. My logic is 1st add a grade (POST), 2nd get the gradeID (GET), 3rd add grades to students (PUT). My problem is that I have to use the gradeID in the API call to add the grades.
How do I do using AJAX to get the result from one call and then pass to another call?
here is my ajax:
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) {
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
$("#responseFieldLabel").removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
Is there a way tho have an ajax inside of other?

Uncaught syntax error during photo upload using AjaxFileUpload

if(myData)
{
$('.overlay_content').html('<img src="'+baseurl+'resource/img/loading.gif" width="30"> LOADING');
$('#loader_overlay').fadeIn(100);
$.ajaxFileUpload({
url:baseurl+"invoice_settings/manage/post_settings/",
secureuri :false,
fileElementId :'invoice_logo',
dataType : 'JSON',
data : myData,
success : function (data)
{
var data = $.parseJSON(data);
$('.overlay_content').html('<img src="'+baseurl+'resource/img/tick.jpg" width="30"> Updation Successfull<br/>');
$('#loader_overlay').fadeOut(5000);
$("#settings_form").data('bootstrapValidator').resetForm();
}
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
});
}
This is my js file. when I run my page the data is not uploading and it returns uncaught syntax error. I added handle error function after getting the error "jQuery.handleError is not a function". After adding handleError function now its returning this error.please help me
There are plenty of answer available over internet. whenever you stuck do initial workaround as suggested.
How to use ajax in codeigniter: https://www.formget.com/codeigniter-jquery-ajax-post/
Sample code:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}

Unexpected token for ajax request

I am using json with jquery's ajax. There are two options for results in this code:
one of them null result
one of them is html result for example ...
When I used firefox this code result not enter if(sdata!="") or sdata!=null
If I try to return with json type it's return, but I don't return html token. It returns an exception
unexcepted token <
How can I solve?
$.ajax({
url: '#Url.Action("RefreshPage", "VeriAktarim")',
type: "POST",
data: { key: id },
success: function (sdata) {
if (sdata != "") {
$("#" + change).closest("tr").replaceWith(sdata);
}
},
error: function (req, status, error) {
alert(status + "error" + error);
}
});

wrong ajax callback invoked using cordova

In my jqm app I make a POST using jQuery $.ajax sending and receiving json data. Everything is fine in the browser and on iPhone; on Android I noticed that when this server response is like this:
{ "code" : 500,
"errorMsg" : "bla bla bla",
"errors" : null,
"status" : "INTERNAL_SERVER_ERROR",
"success" : false
}
the ajax invokes the "error" callback and not the "success". This happens only on android and only if I include corova-2.0.0. js on the project. Any help?
I'm using cordova-2.0.0 with jqm 1.3.1 and jQuery 1.9.1
Here's my code:
var ajax = $.ajax({
type: "post",
url: url,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
timeout: 30000
});
var success = function (d) {
if(d.success==true && obj.success)
obj.success(d.data);
else
{
var msg = parseErrors(d);
console.log(msg);
//open page passing results
obj.msgBus.fire("RequestResult", {
callback: function(){ obj.msgBus.fire("Welcome");},
success: false,
text: msg
});
}
};
var error = function (xhr, status, e) {
console.log('error ajax url:[' + url + '] status:[' + status + '] error:[' + e + ']');
if (obj.error) {
if ((typeof e == 'string'))
obj.error({
statusText: e,
code: xhr.statusCode,
text: xhr.responseText
});
else {
e = $.extend(e, {
statusText: status
});
obj.error(e);
}
}
};
var complete = function () {
if (obj.complete) {
obj.complete();
}
};
var parseErrors = function(d){
console.log( d);
if(d.errors==null){
return d.errorMsg;
}
else
{
var res="";
for (var i=0;i< d.errors.length;i++){
res+= "{0}: {1} <br/>".format( d.errors[i].field, d.errors[i].errorMsg);
}
return res;
}
};
ajax.success(success).error(error).complete(complete);
where data is an object like this:
{
"date" : 1371679200000,
"idBeach" : "1",
"idStuff" : 3,
"idUser" : "8",
"numStuff" : 1
}
Try this, it works for me
$.ajax({
async: false,
type: "POST",
url: "Your_URL",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, object) {
alert(obj.Data);
});
},
error: function () {
alert("There was an error loading the feed");
}
});

Can I return custom error from JsonResult to jQuery ajax error method?

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});

Resources