0
votes

First attempts at Web API and a little confused.

I've set up a basic Delete in Web Api:

public HttpResponseMessage Delete(string id)
{
    HttpResponseMessage response = new HttpResponseMessage();
    response.ReasonPhrase = "User successfully deleted";
    response.StatusCode = HttpStatusCode.OK;

    return response;
}

and calling it via jquery ajax:

deleteUser: function (data) {
    var self = this;
    $.ajax({
        type: "DELETE",
        url: urlPath + data.Id,
        success: function (response) {
            alert("Success: " + response.status + " : " + response.statusText);
        },
        error: function (response) {
            alert("Error: " + response.status + " : " + response.statusText);
        }
    });
}

This works... Chrome developer tools say StatusCode: 200 User successfully deleted.

Unfortunately the alert from ajax success just says "Success : undefined : undefined", and when breaking inside the success function in Chrome, the response var is blank

How do I retrieve the Status Code/Message in the ajax call to display onscreen?

Thanks

1
rather than response.statusText try response.responseText - Jacek Glen

1 Answers

2
votes

The parameters of jQuery's ajax.success callback function are:

function(PlainObject data, String textStatus, jqXHR jqXHR)

As you can see, the first parameter is the raw response body. if you need the HTTP status code and text, use the jqXHR (3rd parameter) data:

success: function(data, status, xhr)
         {
         alert("Success: " + xhr.status + " : " + xhr.statusText);
         }