Quantcast
Channel: Geekswithblogs.net
Viewing all articles
Browse latest Browse all 3624

jQuery 1.9.1+ Ajax Post is Failing even though it has a 200 Status

$
0
0

Originally posted on: http://geekswithblogs.net/Aligned/archive/2013/05/08/jquery-1.9.1-ajax-post-is-failing-even-though-itrsquos-a.aspx

I’m using my DataService and AjaxService for JavaScript and upgraded to jQuery 1.9.1. One of my post methods, which was working before, started hitting the deferred fail, instead of the deferred’s done, even though the status code was 200. This method is not returning any JSON to the caller. The 1.9 upgrade guide states “Prior to 1.9, an ajax call that expected a return data type of JSON or JSONP would consider a return value of an empty string to be a success case, but return a null to the success handler or promise. As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error. Use the error handler to catch such cases.”. This question on the forums lead me to the upgrade guide and “Identifier” says to return a 204 instead. I change my WebApi method to return a 204 and now it’s working again.

I now am using return this.Request.CreateResponse(HttpStatusCode.NoContent);

Here’s the method:

[System.Web.Mvc.HttpPost]public HttpResponseMessage UpdateAlias(JObject jsonData)
{// http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling// http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methodsint assetId = 0;int userId = 0;string alias = string.Empty;try
    {
        assetId = jsonData["AssetId"].Value<int>();
        userId = jsonData["UserId"].Value<int>();
        alias = jsonData["Alias"].Value<string>();if (assetId == 0)
        {thrownew ArgumentException("Asset Id is required.");
        }if (userId == 0)
        {thrownew ArgumentException("User Id is required.");
        }if (string.IsNullOrWhiteSpace(alias))
        {thrownew ArgumentException("Alias is required and cannot be empty.");
        }// more code here…
        // notice the noContentreturnthis.Request.CreateResponse(HttpStatusCode.NoContent);
    }catch (Exception ex)
    {this._logger.Warn(string.Format("Error in UpdateAlias assetId:{0}, userId:{1}, new alias: {2}", assetId, userId, alias), ex);thrownew HttpResponseException(new HttpResponseMessage
                                        {
                                            StatusCode = HttpStatusCode.InternalServerError,
                                            Content = new StringContent("Error!")
                                        });
    }
}

Viewing all articles
Browse latest Browse all 3624

Trending Articles