Json check if certain element has been received - javascript

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

Related

How to write basic Error Handling when using AJAX JSON

I'm not as clued up when it comes to back end development but have this small task of adding some error handling to the code that you see below. All I'm looking to do is display the potential error responses to the #results tag if they occur. It only needs to be something basic as the code itself should leave very little room for errors to occur anyway. Any help would be greatly appreciated. Let me know if you have any questions. Thanks for your help.
$('#hierarchyBtn').click(function() {
$.ajax({
url: "libs/php/getHierarchy.php",
type: 'POST',
dataType: 'json',
data: {
geonameId: $('#selHieGeonameId').val(),
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
var names = result['data'].map(function(geoname){return geoname.toponymName}).join(", ");
$('#results').text(names);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// my error code
}
});
});
If the error you want the display is return by you for instance validation, you can access the erroMessage in the error() callback function but passing errors as parameter and access it with errors.message.
I will display a generic error for all error not related to validation and the validation error if any but, this depends but what you essentially need is to catch the errors that you thrown yourself and display a generic error for anything else, may not be ideal but works
error: function(error) {
// my error code
if(error.statusCode !== 412) {
$('#results').text('A Generic error occured on the server')
}
// Validation error
if (error.statusCode === '412') {
$('#results').text(error.message);
// or $('#results').text(error.errorName)
}
}

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. req.body.options exists and is an array. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. The printed req.body looks like this:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. The problem is not in express, as a request through Postman using the same data and it works. The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense.
I have no idea what causes this error.
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify.
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});

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

Need xml data to keep POST-ing every 2 seconds until a response is received

This is a very small application for a prototype/experiment. A device is going into sleep every so often to save battery life and a user will access a local webpage and press a button to change something with the device--this sends a POST to the device using the javascript code below.
Since the device can be sleeping when the user presses a button it will miss the POST. I know this is bad practice but I basically need the webpage to keep POST-ing (don't even know if I'm using the terminology correctly) or sending data until it receives the response. I tried a while loop but it only sent it once, maybe I put it in the wrong place.
function execPOST(url, postData, callback) {
var postRequest = newAjaxRequest();
postRequest.onreadystatechange = function() {
if (postRequest.readyState == 4) {
if (postRequest.error) {
callback(1, "Request had an error.");
alert('postRequest Error');
} else {
var status;
try {
status = postRequest.status;
} catch (err) {
callback(1, "Failed to get HTTP status from server.");
return;
}
if (status == 200 || status == 0) {
callback(0, postRequest.responseText);
} else {
callback(1, "POST: Unexpected HTTP Status: "
+ postRequest.status);
alert('POST: Unexpected HTTP Status: '
+ postRequest.status);
}
}
}
}
if (postRequest.overrideMimeType){
postRequest.overrideMimeType("text/xml");
}
postRequest.open("POST", url, false);
//I tried adding this while loop hoping it would keep sending but it only sent once
while (postRequest.readystate != 4)
{
setTimeout('',2000);
postRequest.send(postData);
}
return postRequest;
}
I suggest looking at socket.io to "ping" the device in a loop until it wakes up, THEN send the POST request.
have you considered to use jquery?
function ping () {
$.ajax (
<url>
, {
error: function ( jqXHR, textStatus, errorThrown ) {
}
, timeout: 5000 // in ms
, type: 'POST'
}
}).done(function ( data, textStatus, jqxhr ) {
// whatever
}).fail(function ( jqxhr, textStatus, data ) {
// note that the order of arguments is different from that of the success handler ('done') !
if (textStatus === 'timeout') {
ping();
}
else {
// ... more error handling
}
});
for more info, consult the docs.

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources