Ajax response status 200 but shows error message - javascript

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}

As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info

Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

Related

how to show custom REST API error messages in javascript client

I have Java REST API generated using swagger, in that if client is unauthorized then then i am sending custom error messages in response
public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, String authBase64String) throws NotFoundException {
// do some magic!
ErrorRequestObject erb;
ArrayList <ErrorRequestObject> erbs = new ArrayList<ErrorRequestObject>();
if (authBase64String == null)
{
erb = new ErrorRequestObject(); erb.setError("Missing Authorization in Header"); erb.setPath("Header:Authorization");
erb.setProposedSolution("Authorization Header should contain user:pwd:nhPath as Base64 string");
erbs.add(erb);
}
if (erbs.size() == 0)
{
//success code here
}
else
{
return Response.status(400).entity(erbs).build();
}
}
I call this API using ajax as follows,
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
}
});
now when i call this API with ajax call it without authorization in header it gives me 400 status that is fine as expected but how do i get error object created with java ? can anyone please tell me how do i get this error object at javascript client ?
Something like this:
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
},
error: function(err) { /* your code here*/})
});
You can use the error function like
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
Where,
The jqXHRobject, textStatus - a string describing the type of error that occurred and an optional exception object as errorThrown, if one occurred. So, you can manipulate the statusCode and everything from this parameters like,
jqXHR.status == 400

Access JSON Ajax Response data

I have added a property to a JSON data but I cannot access the data on JS it does not show. I am not new to Ajax and JSON but it is a apparent that I still have gaps in my knowledge when it comes to Ajax. Please help me understand how i can append data to my Ajax response.
I have this in a PHP controller class:
$x = '5';
if($request->ajax()){
return response()->json([
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
I want to access the total_questions property with JS/JQuery..
My JS AJAX callback is here:
console.log('errors -> ', data.total_questions); - returns undefined
$.ajax({
type:"POST",
url: APP_URL+"selfEvaluation/save",
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log('data -> ', data);
console.log('errors -> ', data.total_questions);
if(data.status == 422){
// alert('422');
}
}
});
This is my console result
error: function(data){
is an incorrect method signature. See the definition at http://api.jquery.com/jquery.ajax/.
It should be
error: function(jqXHR, errorThrown, textStatus){.
You'll need to access the jqXHR.responseJSON property. So:
console.log('errors -> ', jqXHR.responseJSON.total_questions);
But I would question why you're returning a "500" status code for this request, when it appears to be a valid response. "500" means "Internal Server Error", which implies the server crashed, when it appears that it did not. If you return a "200" ("OK") status, your ajax code will go into the "success" callback and you can directly reference the "data" object in the callback to read your data.
try this if you will get a json response from your browser.
if($request->ajax()){
$result = array(
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
echo json_encode($result);

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

Angularjs http request doesn't go in errorCallback

I'm using angularjs to call my Rest web services but I have a problem with error handle.
This is one of my http calls:
$http({
method: 'POST',
url: "tr"+licenseSelected,//angular need string in url
headers: {'Content-Type': 'application/json'},
data : updatedLicense,
beforeSend: function() {
waitingModal.showPleaseWait();
},
complete: function() {
setTimeout(function(){
waitingModal.hidePleaseWait();
}, 1000);
}
}).then(function successCallback(response) {
if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});
I would like to show 500 page if an error occurred during http request (for example server down or wrong url), but errorCallback is never called.
Is there an error in my code? where is my fault?Thanks
This is an example of response that I can't handle in error code:
{
"status":422,
"exception":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message":"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"",
"stacktrace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:115)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
......"
}
Web service example
#Override
#RequestMapping(value = { "/license"}, method = RequestMethod.POST)
public #ResponseBody Response createLicense(#RequestBody ClientLicenseForm clientLicenseForm) {
try{
administrationService.createLicense(clientLicenseForm);
return new Response(true, true, "Your license has been created!", null);
}catch(Exception e){
ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
LOG.error("Threw exception in AdministrationControllerImpl::createLicense :" + errorResponse.getStacktrace());
return new Response(false,false,"Error! Your license hasn't been created!",errorResponse);
}
}
This may be the problem(it wrap json response inside another object), but how can I fix it?
UPDATE
I have fixed with this code, I'll test it
}).then(function successCallback(response) {
if (typeof response.data.success == 'undefined'){
window.location.href = "/ATS/500";
}else if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else if(response.data.success==false) {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});
Redarding you comments you get a json response (i think with 200 header)
The error callback will not fire while in the header response was 200 code.
You can manage it in two ways:
Rewrite backend side to return proper status header code
Check if response valid in successCallback
if (response.data.exception) {
window.location.href = "/ATS/500";
}
NOTE: but basically it's wrong that server return this type or error with stacktrace.
Exceptions handling examples

Cannot access data in JSON response

I am trying the access the json response from the server, using the following code. According to firebug, my server is outputting what looks like a valid json response as follows:
{"result":"error","message":"This group is not empty"}
my JavaScript is as below, but when I try to alert() the data from json response, I get nothing
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
alert(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
alert(data.result); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}
UPDATE:
//data = jQuery.parseJSON(data);
console.log(data);
Console.log is giving me this
readyState
4
responseJSON
Object { result="error", message="This group is not empty"}
responseText
"{"result":"error","mess...is group is not empty"}"
status
400
statusText
"Bad Request"
and
data = jQuery.parseJSON(data);
console.log(data);
is giving this error
SyntaxError: JSON.parse: unexpected character
...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i) {if("string"...
The status 400 and "bad request" is something I am oputiing in my php headers to show that there was an error backend
The error handler of an $.ajax request has the signature
Function( jqXHR jqXHR, String textStatus, String errorThrown )
[…] 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.
Change your function to
error: function(jqXhr) {
var data = jqXhr.responseJSON; // you saw this in your console.log
if (data) {
…
} else {
// there might be other errors, where you don't get the server message
}
}
The problem is with parsing the JSON data in the javascript :
Before using the json data
data=jQuery.parseJSON(data);
alert(data.result);
Try this.
Use jQuery.parseJSON and might I suggest to use console.log instead of alert, like this:
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
data = jQuery.parseJSON(data);
console.log(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
data = jQuery.parseJSON(data);
console.log(data); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}

Categories

Resources