Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 402
coding_hero Avatar asked Mar 19 '23 17:03

coding_hero


2 Answers

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.

like image 128
coding_hero Avatar answered Mar 23 '23 20:03

coding_hero


Try this (pattern)

updated

$(function () {
    var callback = function (results) {    
        $("#output")
        .append("<p>Submitted successfully to server. Returned data: " 
        + JSON.stringify(results.caseURL) + "</p>")    
    };
    var myobj = {
        "caseURL": {
            "caseURL": "https://cs18.salesforce.com/50060000008ugtSAAQ"
        }
    };

    var request = $.ajax({
        url: "/echo/json/",
        data: {
            json: JSON.stringify(myobj)
        },
        type: "POST",
        dataType: "json"
    });
    request.done(function (data, textStatus, jqxhr) {
        if (textStatus === "success" && jqxhr.responseJSON) {
            console.log(data, jqxhr.responseJSON, jqxhr.responseText);
            if (data.hasOwnProperty("caseURL")) {
                callback(data)
            };
        };
    });
    request.fail(function (jqxhr, textStatus, error_text) {
        if (textStatus != "success") {
            console.log("Update unsuccessful. Status: ", error_text, 
            textStatus, jqxhr.getAllResponseHeaders());
        };
    });
})

updated jsfiddle

see

http://doc.jsfiddle.net/use/echo.html#json

http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings (data, dataFilter, processData)

http://api.jquery.com/jQuery.ajax/#sending-data-to-server

like image 34
guest271314 Avatar answered Mar 23 '23 18:03

guest271314