"error" or "fail" for $.post Ajax call in jQuery - javascript

I'm trying to trigger a Bootstrap Growl message if $.post call fails. How I know if it fails? Because backend part (PHP script) returns this JSON:
{
"success":false,
"errors":{
"usuario":{
"captcha":[
"The captcha is not valid."
]
}
}
}
So I did this in jQuery:
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json').fail(function(result) {
console.log("fail");
$.growl({
icon: "fa fa-paw",
title: "<strong>Error en datos</strong>",
message: "Los siguientes errores ocurrieron",
type: "danger",
allow_dismiss: true,
animate: {
enter: 'animated bounceInDown',
exit: 'animated bounceOutUp'
}
});
});
But none the message or the console.log() works so I don't know if the right is .fail() or .error() or all the time is success and then I need to verify if success at JSON comes with FALSE which means some error.
As a second little question, how I move inside the JSON looking for errors strings for show them as LI inside the message at Growl element?

The fail clause will be triggered if the response contains an http error, for example, a 400 or a 500. If the http response is 200 - ok, then you won't get a failure.

Try this code:
$.post($form.attr('action'), $form.serialize(), function(result) {
//code for success
if (result.success) {
//TODO
}
//code for failure
if (!result.success) {
console.log("fail");
$.growl({
icon: "fa fa-paw",
title: "<strong>Error en datos</strong>",
message: "Los siguientes errores ocurrieron",
type: "danger",
allow_dismiss: true,
animate: {
enter: 'animated bounceInDown',
exit: 'animated bounceOutUp'
}
});
}//if failed
},
'json');

I think you are confusing a captcha failure and an ajax call failure as the same thing, if I am interpreting your question correctly, that is.
The ajax call itself is succeeding, which is why you see none of the ajax failure output. The JSON returned by the SUCCESSFUL call contains information(success:"false") stating that the captcha entry failed to pass it's test. Does that make sense?
You will need to take the success attribute in the result JSON and apply appropriate actions depending on it being a success true or false.

Related

fail() handler also fires on HTTP200 and HTTP202

I have this simple code:
function dlgEditPhase_okClicked(dlgEditPhase, event) {
$.post("/overview/phase/"+dlgEditPhase.projectId,
JSON.stringify({
"phaseName": dlgEditPhase.phaseName,
"begin": dlgEditPhase.begin,
"end": dlgEditPhase.end
}),
function(data) {
dlgEditPhase.close();
location.reload();
},
"json"
).fail(function(data) {
alert(data.responseJSON);
});
}
Problem is, the fail is always fired, even when the POST call returns code 200 or 202.
What am I doing wrong?
Fail can also fire because response is not a valid json

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},

Json check if certain element has been received

I have an ajax call to one of my servlets that does some database manipulation. The question I am asking is, is there and easy way to see if I receive a certain element in my json. For example, I am receiving back a { message: "Some data message" } but if there is an error, I want to send back {error: "my error message"}. Is there a simple way to see if there was an error sent?
The logic I am thinking of is like this (this does not work)
$.post( "database.json", { id: id, info: info})
.done(function( data ) {
if(data.error){
alert(data.error);
} else {
alert(data.message);
}
You can check this with
if (data.hasOwnProperty("error")) {
alert(data.error);
} else {
alert(data.message);
}

ajax uploader success event: unable to get json value

I am using this script
http://hayageek.com/docs/jquery-upload-file.php
for my uploader.
The uploading is great, everything works, my server side script returns a JSON upon successful upload, however, in the success event, i am not able to get the json value
$("#fileuploader").uploadFile({
url: site.url + 'main/upload',
fileName: 'cpp',
multiple: false,
method: "POST",
allowedTypes: "png,gif,jpg,jpeg",
dragDrop:true,
onSuccess:function(files,data,xhr)
{
if(data.error){
//there is an error
} else {
//there is no error
console.log('no errors ' + data.path);
$('.img-thumbnail').attr('src', data.path);
}
},
onError: function(files,status,errMsg)
{
console.log('uplaod failed');
}
});
The JSON returned by my server side script is
(as seen in firebug)
{"error":false,"msg":"Success","path":"http:\/\/www.domain.com\/uploads\/thumb.png"}
However, data.path returns undefined(i use console.log to check), but when I output it with alert(data), the data seems to be intact there.
(p/s: data.error, data.msg also returns undefined value).
Is this something wrong with my logic or i am missing something out?
Use returnType: "json" and
Try to use parseJSON() like,
onSuccess:function(files,data,xhr)
{
data=$.parseJSON(data); // yse parseJSON here
if(data.error){
//there is an error
} else {
//there is no error
console.log('no errors ' + data.path);
$('.img-thumbnail').attr('src', data.path);
}
},

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

Categories

Resources