ashish.gd
ashish.gd

Reputation: 1768

Jquery cross domain ajax request always error

I am trying a to create a simple Jquery mobile application. My set up is as follows:

  1. jQuery client is running on localhost:9090/myapp.
  2. My server is running on localhost:9010/paperboy
  3. Since I am on windows, on the server side I am using a simple server creating using "bottle" which is a python micro framework.
  4. The server returns json on request, which I can clearly see in Chrome or Firefox.
  5. I have validated my response and it is a valid JSON.

The problem I am facing is, that I want my client to read the json from the server response.
But since its a crossdomain issue, it is not able to do so.
Here is my ajax code for the client:

$.ajax({
        url: "http://localhost:9010/paperboy/toi",
        type:"GET",
        data:$(this),
        dataType:"jsonp",
        //jsonp:"callback",   no support on the server

        success:function(result){
            console.log("ajax result: " + result);
        },

        error:function(e){
            console.log("Error :" + e);
        }
    });

and my bottle Server code is:

from bottle import route, run, template, response
from paperboy import getToiNews

''' call http://localhost:9010/paperboy/toi in browser'''

@route('/paperboy/:source')
def index(source='All'):
    print "requesting news list for %s" % source
    resultJson = getToiNews()
    response.content_type = "application/javascript"
    return resultJson

run(host='localhost', port=9010)

However on running the application I initially was getting "ajax origin policy error" which soon went away once I added the content type to my server.
Now the ajax call goes through without errors, but always invokes the "error" handler. I have tried various combinations but all in vain. One thing I could not figure out is adding jsonp support to my server.
I appreciate any help in this matter and thank you in advance for all the help.
Thanks.

Upvotes: 1

Views: 1939

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You said it yourself, since it's a cross-origin call, by default it's disallowed by the SOP.

If you're in control of the server (and you are), you can use CORS to allow the request. That will work on any modern browser. (Though sadly in the case of IE8 and IE9, you'll need a jQuery patch to enable use of the Microsoft-specific XDomainRequest object rather than the standard XMLHttpRequest; the jQuery team refuse to put it in the library. IE10 finally adds cross-domain handling to XMLHttpRequest.)

Alternately, as the response is JSON, you could use the very similar JSON-P instead, which has the advantage of working with all browsers (and without jQuery patches).

Upvotes: 4

Related Questions