I'm new to JSON and have been using it with MVC3 ASP.NET but could somebody shed some light on how to return an error per a JSON result?
I have the following call from my View:
$.ajax({
type: "POST",
dataType: "json",
url: "EditJSON",
data: { FilmID: InputFilmID, Title: InputTitle, Description: InputDescription},
success: function (result) {
alert(result.Message + " updating film " + result.Title);
window.location = "../All";
},
error: function (error) {
alert('error');
}
});
Controller handles the request as a success. What would I pass back for a JSON error so that the error: function handled back at the View?
[AcceptVerbs("POST")]
public JsonResult EditJSON(BobsMoviesMVC2.Models.Film film)
{
filmRepository.Update(film);
return Json(new {Message = "Success", Title = film.Title });
// What would I return for an error here?
}
Thanks!
jQuery uses the HTTP response code to determine success or failure.
HTTP response codes >= 400 are considered errors. HTTP response codes >= 200 and < 400 are considered successes.
Return appropriate HTTP codes from your server-side code to get the behavior you're after.
Confirmed, in .NET you can put:
Response.StatusCode = (int)HttpStatusCode.InternalServerError,
or whatever error status code you wish, right before your JSON return statement. (Thank you Mariah).
Check out the 'error' option of the jquery ajax call to see what you can do with the resulting error on the client-side.
A header with a status code other than 2xx or 3xx, probably a 5xx or 4xx error code.
Related
I am working on building a Django project.
Once the button is clicked, the form will be submitted and some tasks will be performed based on the information from the form. However, in my case, the task can be done properly while there is always error pop up saying: "parsererror SyntaxError: Unexpected end of JSON input".
Here is my AJAX function:
$(document).on('submit', '#productForm', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
url: 'product/',
data: {
region: $("#Region-choice").val(),
country: $("#Country-choice").val(),
product: $("#Product-choice").val(),
dvn: $("#dvn").val(),
reship: $("#reshipCheckbox").val(),
reshipId: $("#reshipTextfield").val(),
validator: $("#Validator").val()}
})
.done(function(){
alert("Product Created!");
})
.fail(function(req, textStatus, errorThrown) {
alert("Something went wrong!:" + textStatus + ' ' + errorThrown );
});
alert("Submitted!");
});
Views function:
def viewCreateProduct(request):
"""The .delay() call here is to convert the function to be called asynchronously"""
if request.method == 'POST':
region = request.POST.get('region')
country = request.POST.get('country')
product = request.POST.get('product')
dvn = request.POST.get('dvn')
reship = request.POST.get('reship')
reshipId = request.POST.get('reshipId')
validator = request.POST.get('validator')
task = createProduct.delay(region, country, product, dvn, reship, reshipId, validator)
return HttpResponse('')
As the error says, you need to return valid JSON from your Django view:
An empty string isn't valid JSON, so make sure your response has valid JSON as its body
Also (although probably not critical in this case) you should set the Content-Type header to application/json instead of text/html which is the default for an HttpResponse. You can use Django's JsonResponse instead or add the correct HTTP header to your HttpResponse object.
I have the following WebGet:
[WebGet(UriTemplate = "GetAssignments/{data}")]
[Description("GetAssignments")]
BASE.BaseResponse<object> GetAssignments(String data);
Called thusly:
var data = JSON.stringify(advancedSearchDataXml);
Helper.Service.Call({
api: 'HomeApi',
url: '?method=GetAssignments/' + data,
method: 'GET',
//data: advancedSearchDataXml,
controlId: '',
showProgress: true,
onSuccess: function (result) {
...
where data is
{"searchquery":
"<SearchQuery>
<genericsearch></genericsearch>
<region>MA</region><market>RL</market>
<recordcount>5000</recordcount>
</SearchQuery>"
}
This fails with a "EXCEPTION: The remote server returned an error: (400) Bad Request" message. What am I doing wrong?
Try removing the ?method= instead have only 'GetAssignments/'+ data .. also add a break point in your controller to make sure the right method is being hit.
I try to get a JSON object from a webservice with
MashupPlatform.http.makeRequest(url, {
method: 'GET',
requestHeaders: {"Accept": "application/json"},
forceProxy: true,
onSuccess: function (response) {
console.log("response: " + JSON.stringify(response));
success(response);
},
onFailure: function (response) {
error(response);
},
onComplete: function () {
complete();
}
});
but in the console every time an empty element ({}) gets logged. If I use curl to request that exact same URL I get the response I need. Is the wirecloud proxy unable to request application/json? In my browsers network analysis I see the request including the correct response, but the success function seems to not get that data.
WireCloud proxy supports application/json without any problem. Although the problem may be caused by other parameters, I think that your problem is related to a bad access to the response data. You should use response.responseText instead of using directly the response object (see this link for more info).
I'm trying to use an ajax call to get json data about my model from my controller. I know 500 error could mean lots of things but I would like to eliminate the possibility of simple error by me.
Console gives me error of: 500 Internal Service Error.
Otherwise I can access it in the url just fine but I don't get anything in the console.
Index.cshtml
function getData() {
$.ajax({
url: "#Url.Action("dataTransfer", "Data")",
type: "GET",
dataType: "json",
success: function(data) {
console.log(data);
},
error: function() {
console.log("failed");
}
});
}
setInterval(function() {
getData();
}, 10000);
DataController
public JsonResult dataTransfer()
{
string DataProvider = "Sample";
var model = from d in db.Data
where d.Name == DataProvider
select d;
return Json(model);
}
500 internal error means your server code is failing, running into an exception because of bad code !
From your code, i can see a problem which could be the cause of your error.
When returning Json from a GET action method, you need to pass JsonRequestBehaviour.AllowGet as the second parameter of Json method.
public JsonResult dataTransfer()
{
string DataProvider = "Sample";
var model = from d in db.Data
where d.Name == DataProvider
select d;
return Json(model,JsonRequestBehavior.AllowGet);
}
Usually in an ASP.NET MVC application, the GET method's are supposed to be returning a view and typically the POST method does some processing on the posted form data/ajax data and return a response, which can be JSON. But if you really want to return Json data from your GET action method, You have to explicitly specify that using the above method we did
Ofcourse, Web API's has a different concept (And implementation behind the scene)
I'm doing an ajax request to an own rest api and trying to print in an alert the message I get.
The point is I'm getting the following error: SyntaxError: Unexpected token :
The code that makes the call is:
$.ajax({
url:"${g.createLink(controller:'report',action:'show')}",
dataType: 'json',
data: {
data: jSon,
},
success: function(data) {
alert(data)
},
error: function(request, status, error) {
alert(error)
},
complete: function() {
}
});
The return value i'm printing in the controller is:
JSON: {"results":"SELECT cliente.edad FROM Cliente cliente,Local local WHERE Local.numero==3 GROUP BY Cliente.edad ORDER BY Cliente.edad undefined""}
And what I'm doing in the controller is:
println "JSON: " + java.net.URLDecoder.decode((String)apiResponse.json)
render java.net.URLDecoder.decode((String)apiResponse.json)
I have also tried with respond instead of render but same error
Try using render as JSON
def results = ['a':'AA','b':'BB']
render results as JSON