JQuery and XHR -- Cross-site JSON POST with CORS

coding_hero picture coding_hero · May 2, 2014 · Viewed 7.2k times · Source

I'm making a small UI to submit a JSON object to an external CastIron server (not that the server type is important to this question) using jQuery. The initial send works fine, but I'm not getting the response from the server. Here's what the jQuery looks like :

$.ajax({
        url: 'http://cirun2/Impact/CreateImpacts',
        type: "POST",
        data: JSON.stringify(myobj),
        dataType: 'text',
        async: false,
        //beforeSend: function(xhr){
        //      xhr.setRequestHeader(
        //},
        complete: function(returned_data) {
                $('#output').append("<p>Submitted successfully to CastIron. Returned data: " + returned_data + "</p>");
        },
        error: function(error_text) {
                console.log("Update unsuccessful. Status: ", error_text);
        }
});

I get the 'Submitted successfully to CastIron. Returned data: [object Object]' message, but it doesn't display the text, and firebug indicates that there's an error.

Firebug response

And here's the full error:

"[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://server.company.com/mr/js/jquery-1.11.0.min.js :: .send :: line 4" data: no]"

The part after the the 200 is the JSON object I'm expecting as a response. I'm not sure how to get to it. The part after the 'Via' is default CastIron headers showing how long each process took. I'm not sure if these are getting issued in the wrong order, or what the problem is.

EDIT (7MAY2014): I've done some more poking around, and I think I left out a crucial piece of information. I'm attempting to use CORS. Here's my headers. Is it possible that the headers are correct for the submit, but not correct for the returned value?

Response Headers
Access-Control-Allow-Head...    X-Requested-With
Access-Control-Allow-Orig...    *
Connection  keep-alive
Content-Length  288
Content-Type    application/json; charset=utf-8
Date    Wed, 07 May 2014 14:34:51 GMT
X-Powered-By    Express

Request Headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host    myserver.mycompany.com:4000
Origin  http://ironsides.zayo.com
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0

Answer

coding_hero picture coding_hero · May 8, 2014

It ended up being improper headers from the CastIron server. I had the CI admin fix the return code to '200 OK', and had her add the following headers:

Access-Control-Allow-Origin: *    
Access-Control-Allow-Headers: X-Requested-With

Turns out her response wasn't sending those headers. After reading up on CORS and Debugging CORS in Firebug, I was able to figure it out.