Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an error in an Ajax scenario

I am using ASP.NET MVC with jQuery. I have the following MVC Action that returns a partial page on Success. On Application Error, I am not sure what to send it for correctly handling it at the client side:

public ActionResult LoadFilterSet(int filterSetId)
{
    try
    {
        BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID);
        GeneralHelper.LoadBreadCrumbManager(bcManager, filterSetId);

        ViewData["BreadCrumbManager"] = bcManager;
        return View("LoadFilterSet");
    }
    catch (Exception ex)
    {
        return Content("");
    }
}

Following is my jQuery ajax call. Notice that I am checking for the data length to make sure there are no errors. Please suggest me a better way of doing this.

$.ajax({
    type: "GET",
    dataType: "html",
    async: true,
    data: ({ filterSetId: selectedId }),
    url: link,
    contentType: "text/html; charset=utf-8",
    success: function(data, textStatus) {
        if (data.length > 0) {
            // Clear the local filters first.
            clearLocalFilters();
            $('td.selected-filters table.filters-display').append(data);
        }
    }
});
like image 821
dotcoder Avatar asked May 14 '10 07:05

dotcoder


People also ask

How do I return from AJAX?

Ajax is a very well known method for loading the content of a Web page without manually refreshing it. But the letter “A” in Ajax means asynchronous, meaning that you need to have a callback function that will return the results.

How do you handle errors in AJAX call?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

How do I send a response to AJAX?

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


2 Answers

I would add an error function in your setup of the ajax call. Let the server determine the error message to display and pass it the ajax error handler and let it display it.

success: function(data, textStatus) {          // Clear the local filters first.          clearLocalFilters();          $('td.selected-filters table.filters-display').append(data);          }, error: function (data) {      alert(data.responseText); // use any display logic here } 

In your controller's action, if an error is found

Response.StatusCode = (int)HttpStatusCode.BadRequest;  return Content(errorMessage, MediaTypeNames.Text.Plain); 
like image 78
Rick Avatar answered Sep 19 '22 15:09

Rick


I think you can do return Content(false.ToString().ToLower()); if an error is thrown, and then check if data is not false

if(data != false) {      //do stuff } 

or

if(!data)   alert("Error"); else {   //do stuff } 
like image 24
knepe Avatar answered Sep 21 '22 15:09

knepe