3

In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?

I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).

The jQuery looks like this :

processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
    debugger;
    var requestURL = '/api/participantevent';
    var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
    var jsonArray=JSON.stringify(json);
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: requestURL,
        data: jsonArray ,
        dataType: "json",
        success: function (data) { successFunction(data); },
        error: function (data) { errorFunction(data); }
    });
},

I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?

Just to be clear all I want to do is to return a plain old 2xx with no data.

5 Answers 5

5

As per the documentation:

"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.

So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:

return Ok(new {});

Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.

1
  • Thanks for this response, I appreciate it. I marked the @Luiz response as correct due to it providing me with a little more information but yours covered similar ground, thanks for the effort.
    – glaucon
    Sep 19, 2015 at 4:21
3
+50

As mentioned by @Beyers the return with OK() just works.

I've created the same structure here and worked.

My Controller has this:

[Route("api/participantevent")]
public IHttpActionResult Test()
{
    return Ok("");
}

And at client I've changed your function just to simplify:

processParticipantEvent= function(){
    debugger;
    var requestURL = '/api/participantevent';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: requestURL,
        data: [{'test': '1'}] ,
        dataType: "json",
        success: function (data) { alert('success'); },
        error: function (data) { alert('error'); }
    });
}
1
  • Thanks - what was good about this answer was it gave me the return type (IHTTPActionResult) as well as the mechanism for using it.
    – glaucon
    Sep 19, 2015 at 4:18
0

Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.

var requestURL = './api/participantevent';
1
  • Thanks for your reply, I appreciate it. In fact the URL does resolve OK because the code within the controller is actually executing in response to the .ajax call - it's just that once that has completed jquery takes the response I was sending it (a HTTPRresponseMessage) as being an error and so fires the error handler. Thanks anyway.
    – glaucon
    Sep 13, 2015 at 22:05
0

It seems that if you get an OK response, It is probably not a valid JSON. I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.

1
  • You can also post here the responseText if you need javascript help
    – Sagi
    Sep 15, 2015 at 23:01
0
  1. I usually declare a class like below:

    public class AjaxResult
    {

    private bool success = true;
    private List<string> messages;
    
    public bool Success { get { return success; } set { success = value; } }
    public List<string> Messages { get { return messages; } }
    
    public AjaxResult()
    {
        messages = new List<string>();
    }
    

    }

  2. In the controller, the action(to which the ajax request is made) should have JsonResult as return type.

    [HttpPost]
    public JsonResult Action(string id)
    {
        AjaxResult result = new AjaxResult();
        //Set the properties of result here...
        result.Success = true;
        result.messages.Add("Success");
        return Json(result);
    }
    

3.And your ajax call will look like this:

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: /ControllerName/Action,
        data: { id: "Test"},
        success: function (data) { alert('success'); },
        error: function (data) { alert('error'); }
   });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.