19

I used following jQuery to insert data via Data Service. Event though I got status-response 201 and the data is successfully inserted into my database, the system still regard it as an error and gives me "failed" alert?

What am I missing here?

$.ajax({
    type: "POST",
    url: "http://localhost:49223/Form/WebDataService.svc/XMLForm(guid'1eaef3a0-d6df-45bf-a8f6-3e7292c0d77e')/XMLRecord/",
    data: JSON.stringify(record),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function() {
        alert("Success");
    },
    error: function(xhr) {
        alert("fail");
    }
});

UPDATE:

Debug Message from Fire Bug:

Preferences

POST http://localhost:49223/Form/WebDataService.svc/X...ef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

POST http://localhost:49223/Form/WebDataService.svc/XMLForm(guid%271eaef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

jquery....min.js (line 127)
POST http://localhost:49223/Form/WebDataService.svc/X...ef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

POST http://localhost:49223/Form/WebDataService.svc/XMLForm(guid%271eaef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

201 Created 6.7s

POST http://localhost:49223/Form/WebDataService.svc/X...ef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

POST http://localhost:49223/Form/WebDataService.svc/XMLForm(guid%271eaef3a0-d6df-45bf-a8f6-3e7292c0d77e%27)/XMLRecord/

201 Created


get readyState 4

get responseText "{ "d" : {\r\n"__metadata"...\')/XMLForm"\r\n}\r\n}\r\n} }"

get responseXML null

get status 201

get statusText "Created"
Ivar
  • 6,138
  • 12
  • 49
  • 61
D.J
  • 2,534
  • 4
  • 28
  • 43
  • 1
    Try using Firebug to view the http response from the server. This might tell you why it's failing. – tbreffni Feb 11 '10 at 00:13
  • Could you please advice me where to look into i am new to consuming ADO.Net in Ajax. I used firebugs however I did not find any error there. I updated the log from fireBug – D.J Feb 11 '10 at 00:49
  • Strange. As far as I can see, `201` is considered a success in JQuery. – Pekka Feb 11 '10 at 00:56
  • I got the same. 201 as failed, thats strange – heffaklump Jul 06 '10 at 11:40

6 Answers6

61

You have to send { dataType: 'text' } to have the success function work with jQuery and empty responses.

Ruben Stolk
  • 12,386
  • 2
  • 18
  • 12
  • 2
    Thanks - I had dataType: "json" and was baffled by this. – Neil Thompson May 17 '13 at 17:15
  • Worked for me too. I spent days on this! I wonder why this is. – sshirley Jun 12 '14 at 00:27
  • 8
    If you look at the source https://github.com/jquery/jquery/blob/master/src/ajax.js#L706 - jquery is checking to see if the status is first 204, then if it's 304, otherwise it tries to use the result of running the response through a converter... The JSON converter throws an exception apparently on an empty string/no content which returns an error even though the status is success. Assuming that with the text converter, jQuery doesn't have trouble parsing an empty response body. Seems like a silly hack - and arguably jQuery isn't acting as expected in this scenario – Mark G. Sep 29 '14 at 20:45
  • This worked for me too, although i am sending Content("Success", "application/json") but changing dataType:text made every thing work. – Zafar Apr 06 '17 at 10:08
  • Ok its 2018 and this solution is the most creative and easy one! Thank you. – Burhan Kashour May 15 '18 at 16:46
11

Solution:

even though I still cant work out how I getting error from previous code, I got this alternative solution which works for me. (at least for now).

would love to hear more ideas

thank you all

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "http://localhost:49223/Form/WebDataService.svc/XMLForm(guid'1eaef3a0-d6df-45bf-a8f6-3e7292c0d77e')/XMLRecord/",
            data: JSON.stringify(record),
            complete: function(xhr) {
                if (xhr.readyState == 4) {
                    if (xhr.status == 201) {
                        alert("Created");
                    }
                } else {
                    alert("NoGood");
                }
            }
            //                
            //                success: function(data) {
            //                    alert("Success");
            //                },
            //                error: function(xhr) {
            //                    alert("fail" + xhr);
            //                }
        });
D.J
  • 2,534
  • 4
  • 28
  • 43
  • I also had the same problem....Turned out to be what "YourParadigm" said below.... – postalservice14 Dec 19 '11 at 21:52
  • I have exactly the same issue. The strange thing is that it was working for awhile. Then a custom header was added to the service calls and ever since then I was unable to use the "success" attribute. Now the real trick is to pass in a custom function for a success and not have to do the xhr.readystate check in every function. – Chris Jul 25 '12 at 21:34
  • This should not be the accepted answer as this solution is practically circumventing the error message by handing it manually. IMO, the accepted answer should be Ruben Stolk's. – leojh Sep 12 '13 at 21:28
4

This happens not because a 201 with no content is necessarily considered invalid but because parsing the empty string ("") is a JSON parse error.

This behavior can be changed globally or per-request by setting a dataFilter.

$.ajaxSetup({
    dataFilter: function(data, dataType) {
        if (dataType == 'json' && data == '') {
            return null;
        } else {
            return data;
        }
    }
});
Steve
  • 6,618
  • 3
  • 44
  • 42
2

I use jQuery_2.1.1 and had similar problem PUT went to error() handler. My REST api call principal is

  • PUT to named key path (/rest/properties/mykey1): 204=Updated existing object, 201=Created new object and return Location header, XXX=anything else most like an error
  • POST to unknown key path (/rest/properties): 201=Created new object and return Location header, XXX=anything else most like an error

Http status 204 is NoContent so jQuery was fine with it, but 201=Created was expecting json body object but I returned zero length body part. Resource address was given in a location response header.

I may return json object depending on few corner cases so had to use datatype:"json" attribute. My jQuery solution was error() check for 201 status and call success() function.

$.ajax({
    url: "/myapp/rest/properties/mykey1",
    data: jsonObj, 
    type: "PUT",
    headers: { "Accept":"application/json", "Content-Type":"application/json" },
    timeout: 30000,
    dataType: "json",
    success: function(data, textStatus, xhr) {
        data="Server returned " + xhr.status;
        if (xhr.status==201) data+=" "+xhr.getResponseHeader("location");
        $("#ajaxreply").text(data);
    },
    error: function(xhr, textStatus, ex) {
        if (xhr.status==201) { this.success(null, "Created", xhr); return; }
        $("#ajaxreply").text( textStatus + "," + ex + "," + xhr.responseText );
    }
});     
Whome
  • 10,181
  • 6
  • 53
  • 65
2

I had this happen to me earlier. My problem was not including a '.json' extension at the end of my query string, so I was getting XML back. jQuery choked on trying to parse the xml as json, causing the error handler to get called.

  • I have a query string looking like this: `/self-service/api/v1/user/` - adding `?format=json` to the end does not work, even though this will make the web service api return json rather than xml. – henrikstroem Aug 20 '13 at 13:46
2

I've answered this on other similar thread:

I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.

Community
  • 1
  • 1
Herberth Amaral
  • 3,479
  • 3
  • 33
  • 35